调用父类属性
public class Person {
protected String name = "kuangshen";
}
public class Student extends Person {
private String name = "qinjiang";
public void test(String name) {
System.out.println(name);
System.out.println(this.name);
System.out.println(super.name);
}
}
public class Application {
public static void main(String[] args) {
Student student = new Student();
student.test("秦疆");
}
}
运行结果:
调用父类方法
public class Person {
public void print() {
System.out.println("Person");
}
}
public class Student extends Person {
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();
}
}
运行结果:
注意:私有的属性或方法无法继承!
调用父类构造器
public class Person {
public Person() {
System.out.println("Person无参执行了");
}
}
public class Student extends Person {
public Student() {
// 隐藏代码:默认调用了父类的构造器 super();
// 调用父类构造器,必须要在子类构造器的第一行
System.out.println("Student无参执行了");
}
}
public class Application {
public static void main(String[] args) {
Student student = new Student();
}
}
运行结果:
总结
super 注意点
1、super 调用父类的构造方法,必须在构造方法的第一行
2、super 必须只能出现在子类的方法或者构造方法中
3、super 和 this 不能同时调用构造方法
super VS this
代码对象的不同:
this:本身调用者这个对象
super:代表父类对象的应用
前提
this:没有继承也可以使用
super:只有继承条件才可以使用
构造方法
this():本类的构造
super():父类的构造