super 关键字
文章目录
super 关键字1.super关键字1.1**this & super 的比较**1.2super访问成员的格式1.3**super的特点**1.4**面试题**
1.super关键字
能帮助子类快速初始化从父类继承下来的成员变量
1.1this & super 的比较
关 键 字
thisthis表示当前对象,是一个引用,意思是:“我的”,每次创建对象都会在堆区创建一个相应的this和引用指向同一个人堆区空间super父类存储空间的标识,可以理解为父类的对象(但不是对象)
class Son extends Father {
public void show() {
super.show();
method(this);
}
public void method(Father f
) {
System
.out
.println("hello");
}
}
1.2super访问成员的格式
super.成员变量
;
super.成员方法
;
super(参数列表
)
public Student(String name
, int age
, String school
) {
super(name
, age
);
this.school
= school
;
}
1.3super的特点
在子类构造方法默认会有:super( );,所以在访问子类构造方法前会访问父类无参构造方法,并在此前加载所有静态成员和静态代码块访问子类构造方法时会访问父类构造方法,但不会创建父类对象,使用( this / super ) 方法构造方法相当于调用普通方法,新的对象使用new关键字任何一个构造方法第一句话都先会访问父类无参构造方法this/super必须出现在构造方法体内的第一句因为上述条件,所以this & super无法共存super可以访问父类的成员变量 成员方法和构造方法static上下文不能出现this super(static在方法区,在类加载的时候已经加载完毕,是不变的,this super在堆区,是在static之后才调用加载的。)
1.4面试题
class Father {
int num
= 30;
public void show() {
int num
= 40;
System
.out
.println(num
);
}
}
class Son extends Father {
int num
= 20;
public void show() {
int num
= 10;
System
.out
.println(num
);
System
.out
.println(this.num
);
System
.out
.println(super.num
);
super.show();
}
}
public class SuperDemo03 {
public static void main(String
[] args
) {
Zi zi
= new Zi();
System
.out
.println(zi
.num
);
}
}
class Fu {
int num
= 10;
public Fu(int num
) {
this.num
= num
;
}
}
class Zi extends Fu {
int num
= 20;
}
package classwork
;
public class ClassWork06 {
public static void main(String
[] args
) {
Son s
= new Son("Tom", "男");
System
.out
.println(s
.getGender());
Son s1
= new Son();
System
.out
.println(s
.getGender());
}
}
class Father {
protected String name
;
protected static int age
;
static {
System
.out
.println("我是父类静态代码块");
age
= 19;
}
public Father() {
super();
System
.out
.println("我是父类无参构造方法");
}
public Father(String name
) {
super();
this.name
= name
;
System
.out
.println("我是父类全参构造方法");
}
}
class Son extends Father {
private String gender
;
static {
System
.out
.println("我是子类静态代码块");
}
public Son() {
super();
System
.out
.println("我是子类无参构造方法");
}
public Son(String name
,String gender
) {
super(name
);
this.gender
= gender
;
System
.out
.println("我是子类全参构造方法");
}
}