整理自:动力节点基础讲义
super
概述
严格来说,super其实并不是一个引用,它只是一个关键字,super代表了当前对象中从父类继承过来的那部分特征。换句话说,super其实是this的一部分,从父类继承过来的属性和方法,在内存方面使用了super关键字标记
super和this都可以使用在实例方法中
super不能使用在静态方法中,因为super代表了当前对象上的父类型特征,静态方法中没有this,肯定也不能使用super
super使用在构造方法
”super(实参列表);“是通过当前的构造方法调用父类的构造方法
”super(实参列表);“调用父类构造方法时,从本质上说并不是创建一个“独立的父类对象”,而是为了完成当前对象的父类型特征的初始化操作,也是为了代码复用,使用用法见【Java学习 | Javase】继承与多态
super使用在实例方法
当父类中有该实例变量,子类中又重新定义了同名的实例变量,如果想在子类中访问父类的实例变量,super不能省略,因为此时父类的实例变量被隐藏了,实例方法亦是如此
总结:父类和子类中有同名实例变量或者同名实例方法,想在子类中访问父类中的实例变量或实例方法,则super不能省略,其他情况都可以省略
代码展示
1、super并不是一个单独的引用
通过测试,可以看出this是单独使用的引用,而super无法输出编译器提示要输出"super.xxx",可见super不是指向某个独立的对象,也不是保存某个地址
代码
public class Test{
public static void main(String[] args) {
H1 h = new H2();
h.doSome();
}
}
class H1{
public void doSome() {
System.out.println(this);
System.out.println(super);
}
}
输出结果
错误: 需要'.'
System.out.println(super);
^
错误: 需要')'
System.out.println(super);
^
错误: 需要';'
System.out.println(super);
^
错误: 解析时已到达文件结尾
}
^
4 个错误
2、super不能在静态方法中使用
如果是写成System.out.println(super),那么编译器会报出上面的错误而不是现在的错误
代码
public class Test{
public static void main(String[] args) {
System.out.println(this);
System.out.println(super.toString());
}
}
输出结果
错误: 无法从静态上下文中引用非静态 变量 this
System.out.println(this);
^
错误: 无法从静态上下文中引用非静态 变量 super
System.out.println(super.toString());
^
3、静态代码块、静态变量、实例变量的综合测试
分析
静态变量有顺序,故先初始化k,然后依次到t1、t2,由于实例变量的初始化在创建对象时执行,故t1和t2创建之前会先执行j。然后到i、n,接着到静态代码块,再然后到main方法。需要注意的是,执行t1、t2时由于i、n没有初始化(没执行到),故是缺省默认值
代码
public class Test{
public static int k = 0;
public static Test t1 = new Test("t1");
public static Test t2 = new Test("t2");
public static int i = print("i");
public static int n = 99;
public int j = print("j");
static{
System.out.println("静态块");
}
public Test(String str){
System.out.println((++k)+":"+str+" i = "+i+" n = "+n);
++i;
++n;
}
public static int print(String str){
System.out.println((++k)+":"+str+" i = "+i+" n = "+n);
++n;
return ++i;
}
public static void main(String[] args) {
new Test("init");
}
}
输出结果
1:j i = 0 n = 0
2:t1 i = 1 n = 1
3:j i = 2 n = 2
4:t2 i = 3 n = 3
5:i i = 4 n = 4
静态块
6:j i = 5 n = 99
7:init i = 6 n = 100
学习没有捷径,能力增强自信,乐观有益人生!