gpt4 book ai didi

Java Puzzler - 谁能解释这种行为?

转载 作者:行者123 更新时间:2023-12-04 11:38:43 24 4
gpt4 key购买 nike

abstract class AbstractBase {
abstract void print();

AbstractBase() {
// Note that this call will get mapped to the most derived class's method
print();
}
}

class DerivedClass extends AbstractBase {
int value = 1;

@Override
void print() {
System.out.println("Value in DerivedClass: " + value);
}
}

class Derived1 extends DerivedClass {
int value = 10;

@Override
void print() {
System.out.println("Value in Derived1: " + value);
}
}

public class ConstructorCallingAbstract {

public static void main(String[] args) {
Derived1 derived1 = new Derived1();
derived1.print();
}
}

上述程序产生以下输出:

Value in Derived1: 0
Value in Derived1: 10

我不明白为什么 AbstractBase 构造函数中的 print() 总是映射到最派生的类(这里是 Derived1)打印()

为什么不使用 DerivedClassprint() ?有人可以帮助我理解这一点吗?

最佳答案

因为所有不是显式 super 调用的 Java 方法调用都被分派(dispatch)到最派生的类,即使在父类(super class)构造函数中也是如此。这意味着父类(super class)可以从子类行为中获益,但也意味着覆盖方法理论上可以在该类的构造函数之前被调用。

关于Java Puzzler - 谁能解释这种行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1513123/

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