有道难题

天涯浪子 提交于 2020-03-14 03:44:11
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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!