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?
This is exact opposite of Liskov Substitution Principle and how polymorphism works. Since
Banana extends Fruitthere is a requirement that any method that takes aFruitaccepts aBanana.If you have to, you need to check dynamic type and throw exception, the compiler cannot do this for you.