Java中super.的使用
Person类
package com.davis.oop.Demo2;
public class Person {
protected String name="Davis";
public void print(){
System.out.println("person");
}
}
Student类 继承Person
package com.davis.oop.Demo2;
public class Student extends Person {
private String name="Leondavis";
public void print(){
System.out.println("student");
}
public void test2(){
print();
this.print();
super.print();
}
public void test(String name){
System.out.println(name);
System.out.println(this.name);
System.out.println(super.name);
}
}
Application类
package com.davis.oop.Demo2;
public class Application {
public static void main(String[] args) {
Student student=new Student();
student.test2();
System.out.println();
student.test("leondavis");
}
}
student
student
person
leondavis
Leondavis
Davis
子在调用自己无参构造之前必须先调用父的无参构造函数
package com.davis.oop.Demo2;
public class Person {
public Person() {
System.out.println("Person无参构造执行了");
}
protected String name="Davis";
public void print(){
System.out.println("person");
}
}
package com.davis.oop.Demo2;
public class Student extends Person {
private String name="Leondavis";
public Student() {
super();
System.out.println("Student无参构造执行了");
}
public void print(){
System.out.println("student");
}
public void test2(){
print();
this.print();
super.print();
}
public void test(String name){
System.out.println(name);
System.out.println(this.name);
System.out.println(super.name);
}
}
Person无参构造执行了
Student无参构造执行了
student
student
person
super的注意点
- super调用父类的构造方法,必须在构造方法的第一个
- super只能出现在子类的方法或者构造方法之中
- super和this不能同时调用构造方法