gpt4 book ai didi

java - 为什么重载与 Java 中的继承一起工作?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:10:57 26 4
gpt4 key购买 nike

我们知道重载不适用于 C++ 中的派生类。但是为什么这种行为在java中是不同的呢?意味着为什么重载适用于 java 中的派生类?考虑以下来自 Stroustrup 博士常见问题解答的示例

#include <iostream>
using namespace std;
class Base
{
public:
int f(int i)
{
cout << "f(int): ";
return i+3;
}
};
class Derived : public Base
{
public:
double f(double d)
{
cout << "f(double): ";
return d+3.3;
}
};
int main()
{
Derived* dp = new Derived;
cout << dp->f(3) << '\n';
cout << dp->f(3.3) << '\n';
delete dp;
return 0;
}

这个程序的输出是:

f(double): 6.3

f(double): 6.6

而不是假定的输出:

f(int): 6

f(double): 6.6

但是如果我们在 java 中执行此程序,则输出会有所不同。

class Base
{
public int f(int i)
{
System.out.print("f (int): ");
return i+3;
}
}
class Derived extends Base
{
public double f(double i)
{
System.out.print("f (double) : ");
return i + 3.3;
}
}
class Test
{
public static void main(String args[])
{
Derived obj = new Derived();
System.out.println(obj.f(3));
System.out.println(obj.f(3.3));
}
}

最佳答案

之所以有效,是因为 Java 语言规范在 §8.4.9. Overloading 中明确允许这样做:

If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded.

另见 §15.12.2. Compile-Time Step 2: Determine Method Signature .

关于java - 为什么重载与 Java 中的继承一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25231084/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com