这是一个 Java 泛型程序,它使用 set(T t)、get() 和 print(T t) 方法实现自定义接口(interface)。
我使用的类称为 Animal。它采用 T 参数(在本例中为字符串)并为动物命名。
我的问题是我无法在打印函数中访问 Animal 类的任何方法。
Animal<String> a1 = new Animal();
a1.set("Mickey");
public void print(Object o) {
Animal oAnimal = (Animal) o; //Downcasting from Object to Animal.
System.out.println(o.get()); //not accessible, and I don't know how to make it accessible.
//I can only access the methods from Object, not my custom class called Animal.
}
最佳答案
你应该使用
oAnimal.get()
因为那是 Animal
的实例。
请记住,您并未修改 o
,因此它将保留为 Object
。
关于java - 向下转型后如何访问基类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22120021/