接口与继承的课上作业

动手动脑:运行 TestInherits.java 示例,观察输出,注意总结父类与子类之间构造方法的调用关系修改Parent构造方法的代码,显式调用GrandParent的另一个构造函数,注意这句调用代码是否是第一句,影响重大.

源代码:

 

class Grandparent {

 

    public Grandparent() {

        System.out.println("GrandParent Created.");

    }

 

    public Grandparent(String string) {

        System.out.println("GrandParent Created.String:" + string);

    }

}

 

class Parent extends Grandparent {

 

    public Parent() {

        //super("Hello.Grandparent.");

        System.out.println("Parent Created");

       // super("Hello.Grandparent.");

    }

}

 

class Child extends Parent {

 

    public Child() {

        System.out.println("Child Created");

    }

}

 

public class TestInherits {

 

    public static void main(String args[]) {

        Child c = new Child();

    }

}

 

运行截图:

 

经过修改Parent构造方法的代码,显式调用GrandParent的另一个构造函数。

运行结果截图:

 

总结:子类的构造方法在运行之前,必须调用父类的构造方法。通过 super 调用基类构造方法,必须是子类构造方法中的第一个语句。

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

 

源代码;

//编写代码测试特性:子类中,若要调用父类中被覆盖的方法,可以使用super关键字。

//fanyalei 2015.11.09

 

class Father{    //父类

public void Show(){

System.out.println("父类方法被调用.");

}

}

class Son extends Father{  //子类

public void Show(){

super.Show();

System.out.println("子类方法被调用.");

}

}

 

class Override {

   public static void main(String[] args){

   Son a=new Son();

   a.Show();

   }

}

 

运行截图:

 

posted @ 2015-11-09 19:49  Fanyalei  阅读(156)  评论(0编辑  收藏  举报