Super
package com.andy.base.oop.demo01.demo05;
//在java中,所有的类,都默认直接或间接继承object
// Person 人 : 父类
public class Person {
public Person() {
System.out.println("Person 无参构造执行了");
}
protected String name = " Andy";
public void print(){
System.out.println("Person");
}
}
package com.andy.base.oop.demo01.demo05;
//学生 is 人 : 派生类,子类
//子类继承了父类,就会拥有父类的全部方法!
public class Student extends Person{
//ctrl + h
public Student() {
//隐藏代码:调用了父类的无参构造
super();//调用父类的构造器,必须在子类构造方法的第一行
System.out.println("Student无参构造执行了");
}
private String name = "zhongjian";
public void print(){
System.out.println("Student");
}
public void test1(){
print();//Student
this.print();//Student
super.print();//Person
}
public void test(String name){
System.out.println(name);//钟健
System.out.println(this.name);//zhongjian
System.out.println(super.name);//Andy
}
}
package com.andy.base.oop.demo01;
import com.andy.base.oop.demo01.demo05.Student;
public class Application {
public static void main(String[] args) {
Student student = new Student();
// student.test("钟健");
// student.test1();
}
}
note
super注意点:
1.super调用父类的构造方法,必须在构造方法的第一个
2.super 必须只能出现在子类的方法或者构造方法中!
3.super和this 不能同时调用构造方法!
VS this:
代表的对象不同:
this: 本身调用这个对象
super: 代表父类对象的应用
前提:
this: 没有继承也可以使用
super: 只能在继承条件才可以使用
构造方法
this() : 本类的构造
super(): 父类的构造!