SCJP Study Guide:
Declarations, Initialization and Scoping


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend


Previous Next vertical dots separating previous/next from contents/index/pdf Contents
XyzWs SCJP Study Guide: Covariant

Covariant

 

What is Covariant?

That's what covariance essentially means, "If a class is inherited and a feature/method/attribute redefined, a parameter or return type can be changed to be a more specialised type". In the J2SE 5.0 release, it  supports covariant return types, but input arguments are invariant.

Covariant in J2SE 5.0

There is now covariant return type support in the definition of overriding methods in the J2SE 5.0 release. This is great news for those who write class hierarchies. This is a fancy way of saying that the overriding method of a derived class can now return an instance of the derived class when the base class method it is overriding returns an instance of the base class. It's an important design idiom in the support for class hierarchies.

Until the J2SE 5.0 release, it was also true that a class could not override the return type of the methods it inherits from a superclass. You are now allowed to override the return type of a method with a subtype of the original type. What this means is that 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. This feature removes the need for excessive type checking and casting.

You will be able to write the following code in J2SE 5.0:

public class ClassA { }
public class ClassB extends ClassA { }
   
public class MyClass
{
    public ClassA getController()
    {
        ClassA a = null;
        .....
        return a;
    }
}
   
public class MySubClass extends MyClass
{
    public ClassB getController()
    {
        ClassB b = null;
        .....
        return b;
    }
}

 

Before J2SE 5.0, you needed to downcast to take advantage of methods that are present in the derived class but not in the base class. As you've seen, in J2SE 5.0 MySubClass compiles with a different return type specified for getController() than is present in the superclass. You can now use your covariant return type to call a method that is only available in the subtype.

 

 


Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |