关于一个构造方法中this()和super()的执行顺序?
我在一个构造方法中调用第二个自身的构造方法,第二个自身构造方法中又包含一个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());
}} |
免责声明:本内容仅代表回答者见解不代表本站观点,请谨慎对待。
版权声明:作者保留权利,不代表本站立场。
|
|
|
|
|
|
|
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
调用顺序一目了然 |
|
|
|
|
|
|
|