gpt4 book ai didi

java - 继承、动态绑定(bind)、父类(super class)中的构造函数。 java

转载 作者:行者123 更新时间:2023-11-29 05:48:31 28 4
gpt4 key购买 nike

为什么第一个 System.out.println 没有打印值 10?它打印一个 0。首先创建一个新的 Child-object,它调用 Parent 中的构造函数。由于动态绑定(bind),Parent 中的构造函数调用 Child 中的查找。那么为什么在 Child 中查找返回零而不是十?

public class Main332 {
public static void main(String args[]) {

Child child = new Child();
System.out.println("child.value() returns " + child.value());//Prints 0

Parent parent = new Child();
System.out.println("parent.value() returns " + parent.value());//Prints 0

Parent parent2 = new Parent();
System.out.println("parent2.value() returns " + parent2.value());//Prints 5
}
}


public class Child extends Parent {
private int num = 10;

public int lookup() {
return num;
}
}


public class Parent {
private int val;

public Parent() {
val = lookup();
}

public int value() {
return val;
}

public int lookup() {
return 5;// Silly
}
}

最佳答案

Childnum 的字段初始值设定项在 Parent 中的构造函数调用之后执行。因此 lookup() 返回 0,所以 Parent.val 设置为 0。

要观察这一点,请更改 Child.lookup() 以打印出即将返回的内容。

参见 section 12.5 of the Java Language Specification有关创建新实例时执行顺序的详细信息。

关于java - 继承、动态绑定(bind)、父类(super class)中的构造函数。 java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14896340/

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