Why return type of same-named-method should be same in sub-class Java?

后端 未结 1 932
清酒与你
清酒与你 2020-12-22 06:11

My background is C++. I know what is overloading and what is the overriding. I want to ask if I don\'t want to override the method from the parent and want to make my own me

相关标签:
1条回答
  • 2020-12-22 06:40

    Because all methods in Java are "virtual" (i.e. they exhibit subtype polymorphism). C++ also disallows conflicting return types when overriding virtual member functions.

    struct Base {
        virtual void f() {}
    };
    
    struct Derived : Base {
        int f() override { return 0; }
    };
    

    Compiler output:

    8 : error: conflicting return type specified for 'virtual int Derived::f()'
    int f() { return 0; }
    ^
    3 : error: overriding 'virtual void Base::f()'
    virtual void f() {}
    ^
    

    Note that only conflicting return types are disallowed. Different return types are allowed, as long as they are compatible. For example, in C++:

    struct Base {
        virtual Base* f() { return nullptr; }
    };
    
    struct Derived : Base {
        Derived* f() override { return nullptr; }
    };
    

    And in Java:

    class Base {
        Base f() { return null; }
    }
    
    class Derived extends Base {
        @Override
        Derived f() { return null; }
    }
    
    0 讨论(0)
提交回复
热议问题