网站关键字设置格式,网站规划与建设与安全管理,杭州商城网站建设,域名购买哪个网站整理自#xff1a;动力节点基础讲义super概述 严格来说#xff0c;super其实并不是一个引用#xff0c;它只是一个关键字#xff0c;super代表了当前对象中从父类继承过来的那部分特征。换句话说#xff0c;super其实是this的一部分#xff0c;从父类继承过来的属性和方法… 整理自动力节点基础讲义super概述 严格来说super其实并不是一个引用它只是一个关键字super代表了当前对象中从父类继承过来的那部分特征。换句话说super其实是this的一部分从父类继承过来的属性和方法在内存方面使用了super关键字标记super和this都可以使用在实例方法中super不能使用在静态方法中因为super代表了当前对象上的父类型特征静态方法中没有this肯定也不能使用supersuper使用在构造方法 ”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 02:t1 i 1 n 13:j i 2 n 24:t2 i 3 n 35:i i 4 n 4静态块6:j i 5 n 997:init i 6 n 100 学习没有捷径能力增强自信乐观有益人生