7.super VS this
super注意点:
- super调用父类的构造方法,必须在构造方法的第一个
- super 必须只能出现在子类的方法或者构造方法中!
- super和 this 不能同时调用构造方法!
- Vs this:
代表的对象不同:
this:
本身调用者这个对象
super:
代表父类对象的应用
前提
this:没有继承也可以使用
super:只能在继承条件下才可以使用
构造方法
this() 本类的构造
super():父类的构造!
父类Person
package com.wang.oop.SuperThis;
public class Person {
//Person 属性
public String name = "personWang";
//Person 方法
public void print(){
System.out.println("Person 方法");
}
//Person 父类的无参构造函数
public Person() {
System.out.println("父类无参构造函数执行了");
}
}
子类Student
package com.wang.oop.SuperThis;
public class Student extends Person{
//Student 属性
private String name = "studentWang";
//Student 方法
public void print(){
System.out.println("Student 方法");
}
//this/super调用属性
public void text01(String name){
System.out.println(name); //输出结果:setWang
System.out.println(this.name);//输出结果:studentWang
System.out.println(super.name);//输出结果:personWang
}
//this/super调用方法
public void text02(){
print(); //输出结果:Student 方法
this.print();//输出结果:Student 方法
super.print();//输出结果:Person 方法
}
//Student的无参构造函数
public Student() {
//查看输出结果之后,我们发现了父类的无参构造函数也是执行了
//说明当前这个地方有一个默认的隐藏的代码 super();
//有了这个代码才能说明为什么父类的无参构造函数会执行,且在子类的前面
//且这个super();方法必须在子类的无参构造函数中第一行写,否则会报错
super();
System.out.println("子类的无参构造函数执行了");
}
}
启动类
package com.wang.oop.SuperThis;
public class Application {
public static void main(String[] args) {
Student student = new Student();
//测试调用属性方法启动
//student.text01("setWang");
//测试调用方法启动
//student.text02();
//当前启动类的new Student 创建这个对象之后
//自动调用Student的无参构造函数
//输出结果:父类无参构造函数执行了
//输出结果:子类的无参构造函数执行了
//父类在前,子类在后
}
}