Originally posted by Elizabeth Jose:
...CovariantTest2.java:19: not a statement
(String)o.method1();
^
1 error...
Welcome to JavaRanch!
The method returns an Object reference, but you don't
need to do anything with that return value. You can just call the method for its effect...
o.method1();
Alternatively, you can assign the return value to a variable...
Object myObj = o.method();
You can also explicitly cast of the reference to type String...
String myStr = (String)o.method();
An explicit cast like this is required for downcasting -- when it's not clear to the compiler that the type of object does, in fact, match the type of the variable. The cast is the programmer's way of saying, "Trust me, assigning this reference to this variable will be okay at runtime."
But when you're not assigning the reference to any variable, it doesn't make sense to explicitly cast its type, and so this is not a valid statement.
[ May 11, 2007: Message edited by: marc weber ]