Before Java 5.0, when you override a method, both parameters and return type must match exactly. In Java 5.0, it introduces a new facility called covariant return type. You can override a method with the same signature but returns a subclass of the object returned. In another words, a method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.
For example, the following code compiles and the narrower type B is a legal return type for the getObject method in the subclass, Sub.
class A {
}
class B extends A {
}
class Super {
public A getObject() {
System.out.println("Super::getObject");
return new A();
}
}
class Sub extends Super {
public B getObject() {
System.out.println("Sub::getObject");
return new B();
}
public static void main(String[] args) {
Super s = new Sub();
s.getObject();
}
}The output of the above code is:
Sub::getObject
But, the following code will not compile because String is not a legal return type for the getObject method in the subclass, Sub. String does not extends from either A or B.
class A {
}
class B extends A {
}
class Super {
public A getObject() {
System.out.println("Super::getObject");
return new A();
}
}
class Sub extends Super {
public B getObject() {
System.out.println("Sub::getObject");
return new B();
}
public String getObject() {
return "getObject()";
}
public static void main(String[] args) {
Super s = new Sub();
s.getObject();
}
}
Comments
Post a Comment