Friday, July 20, 2018

Can we have different return type in method overriding in java?

Problem statement: can we have different return type in method overriding in java

Yes ! it may differ but their are some limitations. 

Before Java 5.0, when you override 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:
class OverridingExe2 {
    public Object run() {
        System.out.println("object");
        return null;
    }
}
public class OverridingExe1 extends OverridingExe2 {
    public String run() { // covariant return type from java 5.0
        System.out.println("string");
        return null;
    }
    public static void main(String args[]) throws Exception {
        OverridingExe2 r = new OverridingExe1();
        r.run();
    }
}
Output:
string

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...