Can the overridden methods in case of inheritance have different return type ?


  • 4
    T

    Answer : By default we tend to say NO , overridden method in sub class should have same signature as that of in base class.

    But this is half correct , Correct answer is : Overridden method can have different return type only in case if they are returning the sub-type.

    Example :

    public class base {

    base show(){

    System.out.println("base class");

    return new base();

    }
    }

    public class sub extends base{

    @Override
    sub show(){

    System.out.println("sub class");
    
    return new sub();
    

    }
    }

    public class Test{

    public static void main(String []args) {

        sub obj=new sub();
    
            obj.show();
    

    }
    }
    In above example show() method return instance of that class , still its an overridden method.


  • 1
    V

    Yes that is correct. An overriding method can also return a subtype of the type returned by the overridden method. This subtype is called a covariant return type.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.