为什么线
这段代码中System.out.println("GoldenDelicious 无参数构造函数");
没有被调用?
public class Test {
public static void main(String[] args) {
Apple a = new Apple();
System.out.println(a);
System.out.println("---------------");
GoldenDelicious g = new GoldenDelicious(7);
System.out.println(g);
System.out.println("---------------");
Apple c = new GoldenDelicious(8);
System.out.println(c);
}
}
class Apple {
double weight;
public Apple() {
this(1);
System.out.println("Apple no-arg constructor");
}
public Apple(double weight) {
this.weight = weight;
System.out.println("Apple constructor with weight");
}
@Override
public String toString() {
return "Apple: " + weight;
}
}
class GoldenDelicious extends Apple {
public GoldenDelicious() {
this(5);
System.out.println("GoldenDelicious non-arg constructor");
}
public GoldenDelicious(double weight) {
super(weight);
this.weight = weight;
System.out.println("GoldenDelicious constructor with weight");
}
@Override
public String toString() {
return "GoldenDelicious: " + weight;
}
}
代码的输出是
带权重的 Apple 构造函数 Apple 无参数构造函数 Apple:1.0 --------------- 具有权重 GoldenDelicious 的 Apple 构造函数 具有权重 GoldenDelicious 的 Apple 构造函数: 7.0 --------------- 具有权重 GoldenDelicious 的 Apple 构造函数 具有权重 GoldenDelicious 的构造函数:8.0
我浏览了你的代码,你提到的
System.out.println("GoldenDelicious non-arg constructor");
行没有被调用,因为你没有使用 GoldenDelicious 类的无参数构造函数创建任何对象!由于该打印语句驻留在 GoldenDelicious 的无参数构造函数中,因此可以继续创建一个无参数的 GoldenDelicious 对象,并且它可以工作。
public class Test {
public static void main(String[] args) {
Apple a = new Apple();
System.out.println(a);
System.out.println("---------------");
GoldenDelicious goldenDelicious = new GoldenDelicious();
GoldenDelicious g = new GoldenDelicious(7);
System.out.println(g);
System.out.println("---------------");
Apple c = new GoldenDelicious(8);
System.out.println(c);
}
}
干杯!