Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method argument extends class implements interface

Tags:

java

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){...} 
like image 595
Gab Avatar asked May 17 '12 18:05

Gab


People also ask

Can I extend a class that implements an interface?

Note: A class can extend a class and can implement any number of interfaces simultaneously.

Can a method extend a class?

No. You can extend the class and override just the single method you want to "extend".

Do interfaces extend or implement?

Implements is used for Interfaces and extends is used to extend a class.


2 Answers

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.

like image 131
bontade Avatar answered Oct 12 '22 15:10

bontade


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) {...} 
like image 33
Steve McLeod Avatar answered Oct 12 '22 17:10

Steve McLeod