Covariant Return Type
Change Return Type of Subclass
What will be the output of compiling and running the following program:
class Base{
public Object getValue(){ return new Object(); } //1
}
class Base2 extends Base{
public String getValue(){ return "hello"; } //2
}
public class TestClass{
public static void main(String[] args){
Base b = new Base2();
System.out.println(b.getValue()); //3
}
}
The above program will print Hello.
Java Language Reference
Covariant Return Type
Covariant returns are allowed since Java 1.5, which means that an overriding method can change the return type to a subclass of the return type declared in the overridden method. However, Covariant return types do not apply to primitives.
The Java language feature of covariant return types explicitly does not apply to primitives. See JLS 8.4.5 and JLS 8.4.8.3.
Observe that at run time b points to an object of class Base2. Further, Base2 overrides getValue().
Therefore, Base2's getValue() will be invoked and it will return hello.