主函数:
public class Application {
public static void main(String[] args) {
Student student = new Student();
student.test("小花");
student.test1();
}
}
Person类
//在java中,所有的类,都直接或间接继承Object
public class Person /*Object(默认继承Object类)*/{
public Person() {
System.out.println("Person执行了");
}
protected String name = "小明";
public void print(){
System.out.println("Person");
}
Student类继承Person类
public class Student extends Person{ //继承Person类
//隐藏代码:调用了父类的无参构造
public Student() {
super();//调用父类的构造器,必须要在子类构造器的第一行
System.out.println("Student执行了");
}
private String name = "小红";
public void test(String name){
System.out.println(name); //小花
System.out.println(this.name); //小红
System.out.println(super.name); //小明
}
public void print(){
System.out.println("Student");
}
public void test1(){
print();
this.print();
super.print();
}
运行结果
super注意点:
1.super调用父类的构造方法,必须在构造方法的第一个
2.super必须只能出现在子类的方法或者构造方法中
3.super和this不能同时调用构造方法