Covariant Return Type in Java
This feature of Java allows overridden methods to have different return types. Before Java 5.0, overriding a method a concept used in inheritance in which subclass can have same method as provided in superclass with different functionality provided parameters and return type of both methods must match exactly. Covariant return type a new concept was introduced in Java 5.0 in which the type returned by the method in the superclass is of superclass type and this overridden method with same signature in subclass can return an object whose type is of subclass type.
Program to demonstrate Covariant return type:-
class A //Base class
{
A get() //method with return type of base class
{
return this;
}
void message()
{
System.out.println("welcome to covariant return type");
}
}
class B1 extends A //subclass
{
B1 get() //overridden method with return type of sub class
{
return this;
}
}
class inheritance
{
public static void main(String args[])
{
new B1().get().message();
new A().get().message();
}
}
Output:
welcome to covariant return type
welcome to covariant return type
In above program get method is overridden method with covariant return type. Message is a method in base class A. In main get method is called by base class A and sub class B1 and then both call the message method. get() is returning current object of specific type which is determining which object is calling the message method.
0 Comment(s)