Super详解

调用父类构造器,必须要在子类构造器的第一行,否则就会报错

只要写了有参构造,无参构造就没了。
public class Person {
public Person(){//无参构造器
System.out.println("Person无参构造了");
}
protected String name="lisi";
public void print(){//如果改成private,那么私有的东西无法被子类继承
System.out.println("Person");
}
}

public class Student extends Person {
public Student(){
super();//调用父类构造器,必须要在子类构造器的第一行,否则就会报错
//隐藏代码,调用了父类的无参构造
//隐藏的是super();
System.out.println("Student无参构造执行了");
}
public String name="linsi";
@Override
public void print() {
System.out.println("Student");
}
public void test1(){
print();//Student
this.print();//Student
super.print();//Person
}
}

public class Application {
public static void main(String[] args){
Student student=new Student();
// student.test1();
}
}
运行结果:
Person无参构造了
Student无参构造执行了

总结:super注意点:
1.super调用父类的构造方法,必须在构造方法的第一个
2.super必须只能出现在子类的方法或构造方法中
3.super和this不能同时调用构造方法
this注意点:
代表的对象不同:
this:本身调用者这个对象
super:代表父类对象的应用
前提:
this:没有继承 也可以使用
super:只能在继承条件下才可以使用
构造方法:
this():本类的构造
super:父类的构造

posted @ 2025-04-02 20:44  骆驼刺破仙人掌007  阅读(12)  评论(0)    收藏  举报