[Solved] Java generic wildcard function


class Super{
    void superMethod(){}
}
class Sub extends Super{
    void subMethod(){}
}
class Sub2 extends Super{
    void subMethod2(){}
}

static <T extends Super> void processSuper(T input){
    // this is safe and compiles
    input.superMethod();

    // this doesn't compile
    input.subMethod();

    // nor this
    input.subMethod2();
}

Look at the above code snippet. When we use an extends Bound, we don’t know what the actual type will be. The compiler isn’t aware of sub types of any given type, so he would have no way to find out what that method is. And even if he did, then this would effectively mean making this method unusable for any other sub types.

You could of course do it with an instanceof check:

if(input instanceof Sub){
    ((Sub) input).subMethod();
}

This compiles, but it’s considered very bad style (tight coupling).
Better OO design would be to have the superMethod() delegate to the different functionalities of Sub and Sub2.


TL;DR
What you want can’t be achieved because the compiler doesn’t know about subtypes. And even if it did work, it would be terrible OO Design.

solved Java generic wildcard function