gpt4 book ai didi

Java super 构造函数执行顺序

转载 作者:行者123 更新时间:2023-11-29 07:54:04 24 4
gpt4 key购买 nike

我一直在学习 Java Certification Bates and Sierra 一书,但对第 2 章构造函数的解释感到困惑:

public class Animal {
String name;

Animal(String name) {
super();

{System.out.println("Hello");} //I put this in myself

this.name = name;
}

Animal() {
this(makeRandomName());
}


static String makeRandomName() {
int x = (int) (Math.random() * 5);
String name = new String[] {"Fluffy", "Fido",
"Rover", "Spike",
"Gigi"}[x];
return name;
}

public static void main (String [] args) {
Animal a = new Animal();
System.out.println(a.name);
Animal b = new Animal("Zeus");
System.out.println(b.name);
}
}

以下内容来自 Bates 和 Sierra 的书:

Notice that the makeRandomName() method is marked static! That's because you cannot invoke an instance (in other words, nonstatic) method (or access an instance variable) until after the super constructor has run. And since the super constructor will be invoked from the constructor on line 3, rather than from the one on line 7, line 8 can use only a static method to generate the name.

我做了一个实验,我在重载的构造函数中插入了一个 super 调用,我的结果是:

 Hello 
Rover
Hello
Zeus

现在从这些结果来看,似乎重载构造函数和 super 构造函数在静态方法之前执行,因为 Hello 在 Zeus 和 Rover 之前打印。那么,为什么需要静态变量呢?

我错过了什么?

最佳答案

方法 makeRandomName()super 之前被调用。您的 print 语句仅表明您正在使用它在其他构造函数执行后产生的值。要查看差异,请将打印语句直接插入 makeRandomName()

关于Java super 构造函数执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19149391/

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