简体   繁体   中英

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
//....
}

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> {
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM