让我们说我有6个或更多特定的类,每个类具有唯一的变量,但整个方法相同。如何使用通用类访问特定类的方法?甚至有可能还是我必须采取另一种方法?
//Specific Class
package test;
public class Specific<T> {
String name = "John";
int age = 18;
public void specificDetails() {
System.out.println("Myname is " + name + " and I am " + age + " years old.");
}
}
//generic class
import test.Specific;
public class Generic {
public static <E> void printPersonDetails(E person) {
//this is the problem. How can I access this method using generics?
person.specificDetails;
}
public static void main(String[] args) {
Specific specificPerson = new Specific();
printPersonDetails(specificPerson);
}
}
谢谢。
答案 0 :(得分:6)
您必须告诉编译器E
与Specific<T>
相关。像
public static <E extends Specific<?>> void printPersonDetails(E person) {
person.specificDetails();
}