问题描述
费话就少说了,直接上代码:Chinese.javaclass Person { void prt(String s) { System.out.println("father--->" + s); } Person() { prt("A Person."); } Person(String name) { prt("A person name is:" + name); }} public class Chinese extends Person { @Overridevoid prt(String s) {super.prt(s);System.out.println("son--->" + s);} Chinese() { super(); prt("A Chinese."); } Chinese(String name) { super(name); prt("his name is:" + name); } public static void main(String[] args) { Chinese cn = new Chinese(); cn = new Chinese("kevin"); }}按我的理解,输出结果应该是:father--->A person.father--->A Chinese.son--->A Chinese.father--->A person name is:kevin.father--->his name is:kevin.son--->his name is:kevin.但是结果却是:father--->A Person.son--->A Person.father--->A Chinese.son--->A Chinese.father--->A person name is:kevin.son--->A person name is:kevin.father--->his name is:kevin.son--->his name is:kevin.这是为什么呀??请大家指教,谢谢啦!
解决方案
Person() { prt("A Person."); } 这里是关键,子类构造函数实例化的时候,super()是调用父类构造函数,父类构造函数里面的prt已经被override了,所以这个时候调用的子类的prt,而不是调用父类的prt在父类的prt中 @Override void prt(String s) { super.prt(s); System.out.println("son--->" + s); } 有调用父类的super.prt