你好!我正在阅读 Head First Java,但我无法理解以下代码的行为:
public class Dog {
String name;
public static void main(String[] args) {
// make a Dog object and access it
Dog dog1 = new Dog();
dog1.bark();
dog1.name = "Bart";
// now make a Dog array
Dog[] myDogs = new Dog[3];
// and put some dogs in it
myDogs[0] = new Dog();
myDogs[1] = new Dog();
myDogs[2] = dog1;
// now acces the Dogs using the array references
myDogs[0].name = "Fred";
myDogs[1].name = "Marge";
// Hmmm... what is MyDogs[2] name?
System.out.print("last dog name is ");
System.out.println(myDogs[2].name);
// now loop through the array
// and tell all dogs to bark
int x = 0;
while (x < myDogs.length) {
myDogs[x].bark();
x = x + 1;
}
}
public void bark() {
System.out.println(name + " says Ruff!");
}
此代码产生的输出如下:
null says Ruff!
last dog name is Bart
Fred says Ruff!
Marge says Ruff!
Bart says Ruff!
我很难理解这一点,IMO 代码应该运行到某种无限循环。据我了解(并且我之前在 python 中编程过):当类被激活时,main 方法被调用,然后在 main 方法中,创建了另外两个相同类型的类。(现在到了难以理解的部分——>)当新类被创建时,在它的 main 方法中,又创建了 2 个类,依此类推.. 当它创建一个 infinte 时,它怎么会产生上面显示的输出类的数量,因此代码实际上应该永远不会完成运行。
谢谢!