Java 5: Covariant Return Type
Before Java 1.5, when we override a Parent class method then we need to have same return type of method in child class.
From Java 5 onwards, we can override a method by changing its return type, but overriding method's return type should be a sub-type of overridden method return type.
For example,
class Parent {
public Parent getObject() {
return this;
}
}
class Child extends Parent {
public Child getObject() {
return this;
}
public void print() {
System.out.println("Child class method..!");
}
public static void main(String[] args){
new Child().getObject().print();
}
}
From Java 5 onwards, we can override a method by changing its return type, but overriding method's return type should be a sub-type of overridden method return type.
For example,
class Parent {
public Parent getObject() {
return this;
}
}
class Child extends Parent {
public Child getObject() {
return this;
}
public void print() {
System.out.println("Child class method..!");
}
public static void main(String[] args){
new Child().getObject().print();
}
}
Comments
Post a Comment