-6

Why generic wildcard function with upper bound is not allowing to access members of subclass when there is a possibility of entering subclass as a parameter?

  • It's impossible to answer such a general question. Please share some code and highlight what problem exactly you're having. – Mureinik Aug 11 '17 at 18:10
  • 1
    Read this answer: https://stackoverflow.com/a/2723538/342852 – Sean Patrick Floyd Aug 11 '17 at 18:12
  • Welcome to Stack Overflow! Welcome toStack Overflow! Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a [mcve]. Use the "edit" link to improve your *question* - do not add more information via comments. Thanks! – GhostCat Aug 11 '17 at 18:19
  • The same reason any variable is not allowed to access members of a subclass of its type. Because it might be one subclass, or another subclass, or not a subclass at all. – shmosel Aug 11 '17 at 18:31
  • What are you talking about ?_? –  Feb 23 '18 at 08:59

1 Answers1

1
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.

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588