What is covariant return type? - JAVA Interview Questions

What is covariant return type?


A covariant return type lets you override a superclass method with a return type that subtypes the superclass method's return type. So we can use covariant return types to minimize upcasting and downcasting.
class Parent {
Parent foo () {
System.out.println ("Parent foo() called");
return this;
}
}

class Child extends Parent {
Child foo () {
System.out.println ("Child foo() called");
return this;
}
}

class Covariant {
public static void main(String[] args) {
Child c = new Child();
Child c2 = c.foo(); // c2 is Child
Parent c3 = c.foo(); // c3 points to Child
}
}



Click Here to See Answer .....
Did you like this article ?
Subscribe to my RSS feed and get more JAVA Question, and Guideline, Plus a lot more great advice to help your Software Career.

1 comments:

Sandesh said...

http://www.cookingjava.com/2016/03/covariant-return-type-in-java.html?m=1

Check this blog for more details

Related JAVA Questions Posts