- 运行 TestInherits.java示例,观察输出,注意总结父类与子类之间构造方法的调用关系修改Parent构造方法的代码,显式调用GrandParent的另一个构造函数,注意这句调用代码是否是第一句,影响重大!
1.没有super的调用
1 class Grandparent 2 { 3 4 5 public Grandparent() 6 { 7 8 System.out.println("GrandParent Created."); 9 10 } 11 12 13 public Grandparent(String string) 14 { 15 16 System.out.println("GrandParent Created.String:" + string); 17 18 } 19 20 } 21 22 23 24 class Parent extends Grandparent 25 { 26 27 28 public Parent() 29 { 30 31 //super("Hello.Grandparent."); 32 33 System.out.println("Parent Created"); 34 35 // super("Hello.Grandparent."); 36 37 } 38 39 } 40 41 42 43 class Child extends Parent 44 { 45 46 47 public Child() 48 { 49 50 System.out.println("Child Created"); 51 52 } 53 54 } 55 56 57 58 public class TestInherits 59 { 60 61 62 public static void main(String args[]) 63 { 64 65 Child c = new Child(); 66 67 } 68 69 }
运行结果:
GrandParent Created.
Parent Created
Child Created
2.有super的构造调用,且在第一行。
1 class Grandparent 2 { 3 4 5 public Grandparent() 6 { 7 8 System.out.println("GrandParent Created."); 9 10 } 11 12 13 public Grandparent(String string) 14 { 15 16 System.out.println("GrandParent Created.String:" + string); 17 18 } 19 20 } 21 22 23 24 class Parent extends Grandparent 25 { 26 27 28 public Parent() 29 { 30 31 super("Hello.Grandparent."); 32 33 System.out.println("Parent Created"); 34 35 //super("Hello.Grandparent."); 36 37 } 38 39 } 40 41 42 43 class Child extends Parent 44 { 45 46 47 public Child() 48 { 49 50 System.out.println("Child Created"); 51 52 } 53 54 } 55 56 57 58 public class TestInherits 59 { 60 61 62 public static void main(String args[]) 63 { 64 65 Child c = new Child(); 66 67 } 68 69 }
运行结果:
GrandParent Created.String:Hello.Grandparent.
Parent Created
Child Created
3.super方法在输出语句的后面
1 class Grandparent 2 { 3 4 5 public Grandparent() 6 { 7 8 System.out.println("GrandParent Created."); 9 10 } 11 12 13 public Grandparent(String string) 14 { 15 16 System.out.println("GrandParent Created.String:" + string); 17 18 } 19 20 } 21 22 23 24 class Parent extends Grandparent 25 { 26 27 28 public Parent() 29 { 30 31 //super("Hello.Grandparent."); 32 33 System.out.println("Parent Created"); 34 35 super("Hello.Grandparent."); 36 37 } 38 39 } 40 41 42 43 class Child extends Parent 44 { 45 46 47 public Child() 48 { 49 50 System.out.println("Child Created"); 51 52 } 53 54 } 55 56 57 58 public class TestInherits 59 { 60 61 62 public static void main(String args[]) 63 { 64 65 Child c = new Child(); 66 67 } 68 69 }
程序报错!
结论:
通过super调用基类的构造方法,必须是子类的构造方法中的第一个语句.(顺序不能打乱)
1.以final 开头的class类不允许继承
2.以final声明的方法不允许覆盖
3.以final声明的变量不允许更改
4.利用final,可以设计出一种特殊的“只读”的“不可变类”
原文地址:https://www.cnblogs.com/cxy0210/p/11728319.html
时间: 2024-11-13 01:32:26