DailyFrankPeter
DailyFrankPeter

Reputation: 414

java, generics - how to parametrize a class with a type T which BOTH: extends and implements sth

I want to type class members, as well as args for methods, in a type T, which has to be a Node and implement my own interface Linkable.

Essentially, I would like to limit the vars to the small section of the inheritance 'tree' between Node and Linkable. Reason being I don't want to have to do all the casting inside the class, depending if I need to call methods of Node or methods of Linkable.

At the moment in my project I know I'm using only Nodes which implement Linkable, but this condition is not enforced in any way.

Pseudo-code below (only for illustration):

public class MyClass <T extends ??> {

T node1;
Bounds bounds1;

bounds1 = node1.boundsInParentProperty(); //Node specific method

node1.linkableSpecificMethod(); //method defined in Linkable interface
//....
}

Upvotes: 1

Views: 77

Answers (1)

Christian Hujer
Christian Hujer

Reputation: 17945

There are two things that help you:

  • Generics do not distinguish between Interfaces and Classes.
  • Generics support ampersand for listing multiple types.

That said, what you probably want is this:

class YourClass<T extends Node & Linkable> {
}

Upvotes: 3

Related Questions