2011-08-26

Java: Covariant Return Type — a demo & definition

Returning a covariant type is the return of a subclass within an overridden method. An overridden method can only be defined in a subclass which is not related to the returned subclass. Methods can also return interfaces.


// Return type classes:
 
 class SuperClass {
 }
 
 class SubClass extends SuperClass {
}
 
 // Classes demonstrating the covariant return type:
 
 class NotRelatedSuperClass {
     SuperClass getInstance() {
         return new SuperClass();
     }
 }
 
 class NotRelatedSubClass extends NotRelatedSuperClass {
     SubClass getInstance() {
         return new SubClass();
     }
 }