I have the following class and interface:
public class BasicObject{...} public interface CodeObject{...}
I want to create a method in which the argument needs to be of type BasicObject and implements CodeObject. I tried the following code but it doesn't guarantee clazz to be a class that implements CodeObject.
myMethod(Class<? extends BasicObject> clazz){...}
I want to do something like this but it doesn't compile:
myMethod(Class<? extends BasicObject implements CodeObject> clazz){...}
Note: A class can extend a class and can implement any number of interfaces simultaneously.
No. You can extend the class and override just the single method you want to "extend".
Implements is used for Interfaces and extends is used to extend a class.
Your pattern class has to extend BasicObject
and extend/implement CodeObject
(which is actually an interface). You can do it with multiple classes declared in the wildcard definition of the method signature, like this:
public <T extends BasicObject & CodeObject> void myMethod(Class<T> clazz)
Note that it won't work if you do it any of these ways:
public <T extends BasicObject, CodeObject> void myMethod(Class<T> clazz)
This is technically valid syntax, but CodeObject
is unused; the method will accept any classes that extends BasicObject
, no matter whether they extend/implement CodeObject
.
public void myMethod(Class<? extends BasicObject & CodeObject> clazz)
public void myMethod(Class<? extends BasicObject, CodeObject> clazz)
These are just wrong syntax according to Java.
Here is an approach which is a bit verbose, but avoids generics headaches. Create another class which does the extending/implementing:
public abstract class BasicCodeObject extends BasicObject implements CodeObject {...}
Then your method can be:
public <T extends BasicCodeObject> void myMethod(Class<T> clazz) {...}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With