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

Tuning ext4 for performance with emphasis on SSD usage

NetBeans 6.1: Working with Google´s Android SDK, Groovy and Grails