super在继承构造函数中定义和作用
● 在继承中子类的构造函数必须依赖父类提供的构造函数
● super(参数列表)访问父类的构造函数
● super调用父类的构造函数, 必须在构造函数的第一行
public class Person {
public Person() {
}
}
public class Student extends Person {
public Student() {
super();
}
}
有参构造
public class Person {
private String name;
private int age;
public Person(String name, int age) {
}
}
public class Student extends Person {
/**
* 1.如果父类只提供了有参构造函数,那么子类的构造必须依赖父类提供的现有的构造函数
* 2.super(参数列表)去访问父类提供的构造函数,必须明确写出参数
* 3.super必须写在构造函数的第一行
*/
public Student() {
super("小王", 20);
}
}
super访问父类的属性
在子类的方法或构造器中,通过使用super. 属性
特殊情况: 当子类和父类中定义了同名的属性时, 想要调用父类中声明的属性,就需要通过 super . 属性 的方式来表明调用的是父类中声明的属性
public class Person {
// 身份证号
int id = 1001;
}
public class Student extends Person {
// 学生证号
int id = 80;
public void show() {
System.out.println(super.id + " " + id);
}
}
public class Test {
public static void main(String[] args) {
new Student().show();
}
}
super访问父类的方法
在子类的构造器或方法中使用 super.方法名
public class Person {
public void eat() {
System.out.println("人都需要吃饭!");
}
}
public class Student extends Person {
public Student() {
super.eat();
}
public static void main(String[] args) {
new Student();
}
}
super与this的区别
● super( )调用父类的构造函数,必须在构造函数的第一行
● this( )调用本类的构造函数,必须在构造函数的第一行
● super( )和this( )不能同时调用构造函数
●代表的对象不同
this:本身调用者这个对象
super:代表父类对象的引用
●前置
this:没有继承也可以使用
super :只能在继承条件下才能使用.
●构造方法
this( ): 本类的构造
super( ) :父类的构造
区别 | this | super |
---|---|---|
代表的对象 | 本身调用者这个对象 | 代表父类对象的引用 |
前置 | 没有继承也可以使用 | 只能在继承条件下才能使用 |
构造方法 | 本类的构造 | 父类的构造 |