I want to have a Class object, but I want to force whatever class it represents to extend class A and also class B. I can do
A simple way for this problem is inheritance.
public class A { // some codes }
public class B extends A { }
<T extends A>
In java you cannot have a class which extends from two classes, since it doesn't support multiple inheritance. What you can have, is something like so:
public class A
...
public class B extends A
...
public class C extends B
...
In your generic signature, you can then specify that T
must extend C
: <T extends C>
.
You could give a look at Default Methods (if you are working with Java 8), which essentially are methods declared within interfaces, and in Java, a class can implement multiple interfaces.
Java does not have multiple inheritance as a design decision, but you may implement multiple interfaces.
As of Java 8 these interfaces may have implementations.
To use multiple classes there are other patterns:
If the parent classes are purely intended for that child class, but handle entirely different aspects, and were therefore separated, place them in a single artificial hierarchy. I admit to doing this once.
Use delegation; duplicate the API and delegate.
Use a lookup/discovery mechanism for very dynamic behaviour.
public T lookup(Class klazz);
This would need an API change, but uncouples classes, and is dynamic.