This concept is called as covariant return type in java. With this concept we can not change the primitive return types. We can only change the object return types.
This is how covariant return type works. If we override a super class method and if it returns an object , then we can change the return type of that method to, one of its sub classes return type.
Let's look for an example.
public class Super {
//This method returns an object of class Super;
Super get(){
return this;
}
}
In the above code segment I have created a class called super.It has a method called get which returns an object of type Super.
public class Child extends Super {
@Override
Child2 get() {
return new Child2();
}
}
In the above code segment ,I have overridden the get() method of Super class. When overridden I have changed the return type of this method to Child2 . Since Child2 is a sub class of Super class I can do so. Further If I want I can change the return type of this method as "Child" since it is also a sub class of Super.
public class Child2 extends Super {
@Override
Child2 get() {
return this;
}
}
Finally I have created another sub class from super class and overriden the get method as return an object from that class itself.
No comments:
Post a Comment