java-07接口与继承

1.动手实验:继承条件下的构造方法调用

代码:

 1 package demo;
 2 
 3 class Grandparent{
 4     public Grandparent(){
 5         System.out.println("GrandParent Created.");
 6     }
 7     
 8     public Grandparent(String string){
 9         System.out.println("GrandParent Created.String"+string);
10     }
11 }
12 
13 class Parent extends Grandparent {
14        public Parent() {
15             //super("Hello.Grandparent.");
16             super("11");    //只能放在第一句
17             System.out.println("Parent Created");
18            // super("Hello.Grandparent.");
19         }
20     }
21 
22 
23     class Child extends Parent {
24 
25         public Child() {
26             System.out.println("Child Created");
27         }
28 
29     }
30 
31     public class TestInherits {
32 
33         public static void main(String args[]) {
34             Child c = new Child();
35         }
36     }

若不在第一句会报错,通过 super 调用基类构造方法,必须是子类构造方法中的第一个语句。

2.为什么子类的构造方法在运行之前,必须调用父类的构造方法?能不能反过来?为什么不能反过来?

构造函数的主要作用:构造函数是类的一个特殊方法,这个方法用来生成实例时由系统自动调用,是为了完成对象的初始化。构造函数方法名同类名相同且参数为空。子类继承父类后同样继承了父类的构造函数,要通过父类初始化。

3.请自行编写代码测试以下特性(动手动脑): 在子类中,若要调用父类中被覆盖的方法,可以使用super关键字。

 1 class Father
 2 {
 3     public void f()
 4     {
 5         System.out.println("fff");
 6     }
 7 
 8 }
 9  
10 public class Try3 extends Father{
11  
12     public void f()//重载a方法
13     {
14         System.out.println("sss");
15     }
16      
17     public void s()
18     {
19         super.f();
20     }
21      
22     public static void main(String[] args) {
23         Try3 t=new Try3();
24         t.f();
25         t.s();
26     }
27  
28 }

原文地址:https://www.cnblogs.com/lzxw/p/6053869.html