Question

After doing some reading, it appears that it is possible to use the & operator to require multiple extends: Class<T extends Class1 & Class2> classObj;

However, I'm looking for a way to enforce "not" functionality at compile time. I have the example where Banana extends Fruit. However, I'm after something along the lines of:

public abstract class Fruit
{
    public abstract String getFlavour();
}

public class Lemon extends Fruit
{
    @Override
    public String getFlavour()
    {
        return "sour";
    }
}

public abstract class Banana extends Fruit
{
    @Override
    public String getFlavour()
    {
        return "very sweet!";
    }

    public abstract String getBananaRipeness();
}

public class UnripeBanana extends Banana
{
    @Override
    public String getBananaRipeness()
    {
        return "unripe";
    }
}

...
    public String methodThatTakesFruitClassButNotBanana( Class<? extends Fruit ! Banana> fruitClass )
    {
        Fruit fruit = fruitClass.newInstance();
        return fruit.getFlavour();
    }

...
        methodThatTakesFruitClassButNotBanana( Lemon.class ); // I want this to compile.
        methodThatTakesFruitClassButNotBanana( UnripeBanana.class ); // I want this not to compile.

Obviously Class<? extends Fruit ! Banana> is not valid syntax. What approaches would you recommend to enforcing this sort of type hierarchy at compile time?

Was it helpful?

Solution

public String methodThatTakesFruitClassButNotBanana

This is exact opposite of Liskov Substitution Principle and how polymorphism works. Since Banana extends Fruit there is a requirement that any method that takes a Fruit accepts a Banana.

If you have to, you need to check dynamic type and throw exception, the compiler cannot do this for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top