public class Co1 {
public void print()
{
System.out.println("Co1");
}
}
public class Holder3<T> {
private T a;
public Holder3(T a)
{
this.a = a;
}
public void set (T h4)
{
this.a = h4;
}
public T get()
{
a.print(); //here, why cant't i use the method print() in class Co1
return a;
}
public static void main (String[] args)
{
Holder3 h3 = new Holder3 (new Co1() );
h3.get();
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method print() is undefined for the type T
at Holder3.get(Holder3.java:16)
at Holder3.main(Holder3.java:25)
Popeus' help while meant to be helpful, was incorrect. The problem is that T is not Co1, T is some type which is not known as you are writing the code.
Assume for a moment that 'a.print()' was legal, then what would happen if I threw this wrench into the equation:
Holder3<String> stringHolder = new Holder3<String>();
stringHolder.get();
When you create a generic class you are writing for a generic type. It's not known until compilation; and furthermore you can't query the object easily to find information about the generic type(but this is off topic). When you declare and initialize the generic class, you tell it what type T represents, think for a moment of how to use classes such as ArrayList, you usually(and should always be) using generic parameters: ArrayList<String>, ArrayList<Integer>, etc.
So you can't have methods being called on the generic type unless you can ensure that any class which can be passed in as a generic argument, in fact contains the method.
If you'd like a print description, I'd suggest you supply an overloaded toString method and use System.out.println(Object o);
public class Co1{
@Override public String toString(){
....
}
}
public class Holder3<T>{
private T a;
@Override public String toString{
return a.toString();
}
public T get(){
System.out.println(this);
return a;
}
}
Topic below answed by Fubarable :
A solution would be to have your generic variable T be constrained to be only the Co1 class or its child classes:
class Holder3<T extends Co1> {
private T a;
public Holder3(T a) {
this.a = a;
}
public void set(T h4) {
this.a = h4;
}
public T get() {
a.print();
return a;
}
public static void main(String[] args) {
Holder3 h3 = new Holder3(new Co1());
h3.get();
}
}
This will give all T variables access to all public Co1 methods.