27 January 2013

Is it possible to have Overriding method to have different return type than the overridden method?

Before 5.0 when you override a method both parameters and return type should match. But in 5.0 onwards new facility is provided called co-variant return type, where you can override same method with the same signature but subclass of object is returned.

This means that method in the subclass can return an object of sub class of object returned by super class.

Example:



class A
{ }
class B extends A
{    }

class Super
{
public A getObject()
{
System.out.println("return object of super class A");
return new A();
}
}

class Test10 extends Super{
public B getObject()
{
System.out.println("return object of sub class");
return new B();
}
public static void main(String[] args)
{
Super s1 = new Super();
s1.getObject();
Super s2 = new Test10();
s2.getObject();
}
}

No comments:

Post a Comment