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();
     }
 }

Comments

Popular posts from this blog

Apple's evaluating a new JVM

Tuning ext4 for performance with emphasis on SSD usage