Covariant Return Type

One of the pillars of Object Oriented Java language is Polymorphism. Polymorphism allows two or more methods within the same class that share the same name, as long as their parameter declarations are different .  It also allows two or more methods in class hierarchy where child class can have same method name as of parent class, but their signature should be same.

Here is a limitation on overridden methods, they can not have different return types. J2SE 5.0 has come up with a solution for this limitation. Onwards J2SE 5.0 new feature called “Covariant Return Types”.

“As per Covariant Return Types, a method in a subclass may return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.”

Consider following example

  1: class ParentClass 
  2: {
  3: 	public SuperValue getValue(){
  4: 		System.out.println("ParentClass.getValue()");
  5: 		return new SuperValue();
  6: 	}
  7: 	
  8: }
  9: 
 10: 
 11: public class ChildClass  extends ParentClass {
 12: 	
 13: 	public SubValue getValue(){
 14: 		System.out.println("ChildClass.getValue()");
 15: 		return new SubValue();
 16: 	}
 17: 	public static void main(String[] args) 
 18: 	{
 19: 		ParentClass obj = new ParentClass();
 20: 		obj.getValue();
 21: 		obj = new ChildClass();
 22: 		obj.getValue();
 23: 	}
 24: }
 25: 
 26: class SuperValue {
 27: 
 28: }
 29: 
 30: class SubValue extends SuperValue
 31: {
 32: 
 33: }
 34: 

Here ChildClass extends ParentClass as well as override getValue() method. Thing to be noted here that both overloaded methods has different return type , but subclass’s method return type is sub type of parent class method’s return type.


Output:


---------- java ----------
ParentClass.getValue()
ChildClass.getValue()

Output completed (0 sec consumed)

If we edit this code to remove SubClass & ParentClass parent child relationship then we will get following compilation error.

  1: class SuperValue {
  2: 
  3: }
  4: //removed inheritance
  5: class SubValue
  6: {
  7: 
  8: }

Output :

  1: ---------- javac ----------
  2: ChildClass.java:13: getValue() in ChildClass cannot override getValue() in ParentClass; attempting to use incompatible return type
  3: found   : SubValue
  4: required: SuperValue
  5: 	public SubValue getValue(){
  6: 	                ^
  7: 1 error
  8: 
  9: Output completed (1 sec consumed)

pe

Comments

Popular posts from this blog

Composite Design Pattern by example

State Design Pattern by Example

Eclipse command framework core expression: Property tester