This is a Java Generics program that implements a custom interface with set(T t), get() and print(T t) methods.
The class that I use is called Animal. It takes a T argument (String in this case) and gives the animal a name.
My problem is that I can't access any of the Animal class methods in my print function.
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.
}
The problem is that you're still trying to call the method on o
, which is still of type Object
(in terms of the compile-time type of the variable, which is all the compiler cares about).
If you call the method on oAnimal
instead, it will be fine:
System.out.println(oAnimal.get());
(You can't return the result of System.out.println
though, as it's a void method. Nor can you specify a return value for your void method.)
Note that this has nothing to do with generics, really. The code in your question can be demonstrated simply using String
:
Object o = "foo";
String text = (String) o;
System.out.println(o.length()); // Error; Object doesn't have a length() method
System.out.println(text.length()); // Prints 3
Your (edited) question does demonstrate a use of generics, but your cast to Animal
is a cast to a raw type, so it's simpler just to leave generics out of the equation - the reason for the compilation failure has nothing to do with Animal
being generic.
See more on this question at Stackoverflow