我在一个构造方法中调用第二个自身的构造方法,第二个自身构造方法中又包含一个super(),那么想知道在第一个自身构造方法中有没有隐式的super(),父类对象应该是优先于子类对象在堆内存里面出现的吧?最后究竟创建了几个父类对象class Person { private String name; private String location; Person(String name) { this.name = name; location = "beijing"; } Person(String name,String location) { this.name = name; this.location = location; } public String info() { return "name: "+name+ " location: "+location; }}class Student extends Person { private String school; Student(String name, String school) { this(name,"beijing", school); } Student(String n,String l ,String school) { super(n,l); this.school = school; } public String info() { return super.info()+ " school: "+school; }}public class TestTeacher { public static void main(String[] args) { Student s1 = new Student("C","S1"); System.out.println(s1.info()); }}
1 回答
android开发学习视频
TA贡献4条经验 获得超3个赞
Student(n, s)这个构造器里显式调用this(),抑制隐式super(),追溯到Student(n, l, s)里,没有显式this()调用,则隐式调用super(),即Person(n, l)
在以上三个构造器里添加打印语句,结果如下:
Person(n, l) established
Student(n, l, s) established
Student(n, s) established
调用顺序一目了然
添加回答
举报
0/150
提交
取消