Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Inheriting class can not be converted to super class in method parameter

I have this method with a generic class as parameter:

myMethod(Class myclass){
    Superclass superclass = myclass;
}

then I use the method by passing a child class of the Superclass

myMethod(Mychildclass.class)

Netbeans is giving me a warning that I am using generic "Class". However this works fine. If I change the method's parameter to this more specific

myMethod(Class<Superclass> myclass){
    this.superclass = myclass;
}

then I am getting an error when trying to use my method:

incompatibles types: Class<Mychildclass> cannot be converted to Class<Superclass>

So my question: Why is this not working? How can I make Netbeans happy giving me no warning and no error messages?

like image 460
Benedikt S. Vogler Avatar asked Feb 18 '14 11:02

Benedikt S. Vogler


1 Answers

Try this instead:

private Class<? extends Superclass> superclass;

void myMethod(Class<? extends Superclass> myclass){
    this.superclass = myclass;
}
  • If you use Class<Superclass>,
    only Superclass.class is expected.

  • If you use Class<? extends Superclass>,
    Superclass.class or any of its child classes are expected.

like image 147
Stephan Avatar answered Nov 10 '22 19:11

Stephan