Hi All,
The below code is my version of a whizlabs mock question. I am not 100% sure of the solution that is given.
Line 1 compiles fine and gives the result "In Oval". This tells me that it has used the method in the Oval class.
Now its Line 2 which confuses me. The whizlabs solution says that c.getValue() must be cast to a
String as an Object reference was used.
I assumed since String is a subclass of Object and that the Oval class method would be used, then the cast is not needed. I know my assumption is wrong as a cast is definitely needed (i complied the code).
So can any fellow rancher explain why the cast is needed as c.getValue() returns a String?
============================================================
class Circle{
Object getValue(){
return "In Circle";
}
}
class Oval extends Circle{
String getValue(){
return "In Oval";
}
}
public class CovariantTest {
public static void main(String[] args){
Circle c = new Oval();
System.out.println(c.getValue());//Line 1
String s = (String) c.getValue();//Line 2
System.out.println(s);//Line 3
}
}