1
 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

ethereal
  • 13
  • 2
  • `T` can be anything. Not every possible class than can be passed to it is going to have a `display` method. – Michael Aug 01 '20 at 17:36

1 Answers1

3

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");
    }
}
Lungu Daniel
  • 816
  • 2
  • 8
  • 15
  • Thank you! But can you explain why we need to do this.. in many examples I saw just just T is declared. And when I print just the object (System.out.println(obj);) in add function, the correct object is displayed, then why don't the methods work? – ethereal Aug 01 '20 at 17:41
  • 1
    `T` can be anything. And "anything" in java means `Object`. Thus, without any bound, the erasure of a generic parameter is `Object` and one can only call methods defined on `Object`. By adding an upper bound (i.e. `T extends SomeClass`), the erasure is set to `SomeClass` and one can use methods and fields defined on `SomeClass`. – Turing85 Aug 01 '20 at 17:44