Can overridden methods differ in return type?

前端 未结 12 1681
礼貌的吻别
礼貌的吻别 2020-11-22 16:11

Can overridden methods have different return types?

12条回答
  •  天涯浪人
    2020-11-22 16:52

    Yes. It is possible for overridden methods to have different return type .

    But the limitations are that the overridden method must have a return type that is more specific type of the return type of the actual method.

    All the answers have given examples of the overridden method to have a return type which is a subclass of the return type of the actual method.

    For example :

    public class Foo{
    
       //method which returns Foo
      Foo getFoo(){
          //your code         
      }
    
    }
    
     public class subFoo extends Foo{
    
      //Overridden method which returns subclass of Foo
      @Override
      subFoo getFoo(){
          //your code         
      }
    
    }
    

    But this is not only limited to subclass.Even classes that implement an interface are a specific type of the interface and thus can be a return type where the interface is expected.

    For example :

    public interface Foo{
    
       //method which returns Foo
      Foo getFoo();
    
    }
    
     public class Fizz implements Foo{
    
      //Overridden method which returns Fizz(as it implements Foo)
      @Override
      Fizz getFoo(){
          //your code         
      }
    
    }
    

提交回复
热议问题