英文:
Can't call method of a Generic Object in Java
问题
import java.util.*;
class GenericClass<T> {
ArrayList<T> list = new ArrayList<>();
void add(T obj) {
list.add(obj);
}
void callMethod() {
list.get(0).display();
}
}
class Test {
public void display() {
System.out.println("HELLO WORLD");
}
}
class Main {
public static void main(String... args) {
GenericClass<Test> gen = new GenericClass<Test>();
Test t = new Test();
gen.add(t);
gen.callMethod();
}
}
你创建了这些简单的类。Test类对象被传递给add函数,但是我无法使用display方法。它会报错 - 无法找到符号display()
当我只打印对象时,我可以看到它打印出了正确的对象。
请帮忙,我对Java非常新。
谢谢。
英文:
import java.util.*;
class GenericClass<T>{
ArrayList<T> list = new ArrayList<>();
void add(T obj){
list.add(obj);
}
void callMethod(){
list.get(0).display();
}
}
class Test{
public void display(){
System.out.println("HELLO WORLD");
}
}
class Main{
public static void main(String... args){
GenericClass<Test> gen = new GenericClass<Test>();
Test t = new Test();
gen.add(t);
gen.callMethod();
}
}
I have created these simple classes. The Test class object is passed to add function, but I can use the method display. It gives the error - Can't find symbol display()
When I just print the object, I can see that it it prints the correct object.
Please help, I'm very new to java.
Thank you
答案1
得分: 3
你必须将你的泛型类型声明为Test类的扩展,因为T,没有任何扩展,可以是任何类型,甚至可能没有display()方法。
class GenericClass<T extends Test>{
ArrayList<T> list = new ArrayList<>();
void add(T obj){
list.add(obj);
}
void callMethod(){
list.get(0).display();
}
}
class Test{
public void display(){
System.out.println("HELLO WORLD");
}
}
英文:
You have to declare your generic type as an extension of Test class, because T, without any extension, could be any type, even one which don't have a display() method.
class GenericClass<T extends Test>{
ArrayList<T> list = new ArrayList<>();
void add(T obj){
list.add(obj);
}
void callMethod(){
list.get(0).display();
}
}
class Test{
public void display(){
System.out.println("HELLO WORLD");
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论