简体   繁体   中英

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

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 method with different return type and same name, why java not allowing me to do this?

Example:

class X{
    public void k(){

    }
}
public class Y extends X{
    public int k(){
        return 0;
    }
}

Why java not applying hiding concept here? mean class Y should hide X's method. what is the reason behind?

C++ applying Hiding concept.

#include <iostream>
class A{
    public:
        void k(){
            std::cout << "k from A";
        }
};
class B:public A{
    public:
        int k(){
            std::cout << "k from B";
            return 0;
        }
};
int main(){
    B obj;
    obj.k();

    return 0;
}

Because all methods in Java are "virtual" (ie 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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM