public class Apple extends Fruit {
private String name = "apple";
public Apple () {
tellName();
printName();
}
public void tellName() {
System.out.println("Apple tell name: " + name);
}
public void printName() {
System.out.println("Apple print name: " + name);
}
public static void main(String[] args){
new Apple();
}
}
class Fruit {
private String name = "fruit";
public Fruit () {
tellName();
printName();
}
public void tellName() {
System.out.println("fruit tell name: " + name);
}
public void printName() {
System.out.println("fruit print name: " + name);
}
}
我想知道為什麼會輸出4行
以及什麼原因
感謝各位
1.先走第三行代碼進tellName()方法。打印輸出 Apple tell name: null
2.進入Class Fruit 進入public Fruit()方法中的tellName
3.再走第三行代碼進printName()方法。打印輸出 Apple print name: null
4.進入Class Fruit 進入public Fruit()方法中的printName
5.走第二行代碼 給name賦值apple
6.重復走1-打印輸出 Apple tell name: apple -2-3 -打印輸出 Apple print name:apple