class Base { private String name = "base"; public Base(){ tellName(); printName(name); } public void tellName(){ System.out.println("Base tell name: "+ name); } public void printName(String name) { System.out.println("Base print name: "+name); } }
public class Derived extends Base { private String name = "derived"; public Derived() { tellName(); printName(name); } public void tellName() { System.out.println("Derived tell name: " +name); } public void printName(String name) { System.out.println("Derived print name: " + name); } public static void main(String args[]) { new Derived(); } }
输出结果:
Derived tell name: null
Derived print name: base
Derived tell name: derived
Derived print name: derived
思路:在new Derived()的构造器里面,先调用了super(此时Derived的name还没有初始化),然后new Base()(省略super初始化Object了部分),其中的tellName被重写了,所以调用子类的tellName;然后再去执行被重写的printName;然后去初始化Derived的name……
printName
printName
来源:https://www.cnblogs.com/bingtel/p/4194463.html