Can an overriding method have a different return type than the overridden method?
Before Java 5.0, when you override a method, both parameters and return type must match exactly. In Java 5.0, it introduces a new facility called covariant return type. You can override a method with the same signature but returns a subclass of the object returned. In another words, a method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.
For example, the following code compiles and the narrower type B is a legal return type for the getObject method in the subclass, Sub.
class A {
}
class B extends A {
}
class Super {
public A getObject() {
System.out.println("Super::getObject");
return new A();
}
}
class Sub extends Super {
public B getObject() {
System.out.println("Sub::getObject");
return new B();
}
public static void main(String[] args) {
Super s = new Sub();
s.getObject();
}
}
The output of the above code is:
Sub::getObject
But, the following code will not compile because String is not a legal return type for the getObject method in the subclass, Sub. String does not extends from either A or B.
class A {
}
class B extends A {
}
class Super {
public A getObject() {
System.out.println("Super::getObject");
return new A();
}
}
class Sub extends Super {
public B getObject() {
System.out.println("Sub::getObject");
return new B();
}
public String getObject() {
return "getObject()";
}
public static void main(String[] args) {
Super s = new Sub();
s.getObject();
}
}
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?