为什么子类Java中的同名方法的返回类型应该相同? [英] Why return type of same-named-method should be same in sub-class Java?

查看:61
本文介绍了为什么子类Java中的同名方法的返回类型应该相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的背景是C ++.我知道什么是重载,什么是重载.我想问问我是否不想从父级重写该方法,并想使自己的方法具有不同的返回类型和相同的名称,为什么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?

示例:

class X{
    public void k(){

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

为什么Java在这里不应用隐藏概念?表示Y类应该隐藏X的方法.背后的原因是什么?

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

C ++应用隐藏概念.

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;
}

推荐答案

因为Java中的所有方法都是虚拟的"(即它们表现出亚型多态性).重写虚拟成员函数时,C ++也不允许冲突的返回类型.

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; }
};

编译器输出:

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() {}
^

请注意,只有冲突返回类型是不允许的.允许不同的返回类型,只要它们是 compatible 即可.例如,在C ++中:

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; }
};

在Java中:

class Base {
    Base f() { return null; }
}

class Derived extends Base {
    @Override
    Derived f() { return null; }
}

这篇关于为什么子类Java中的同名方法的返回类型应该相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆