码迷,mamicode.com
首页 > 其他好文 > 详细

接口与继承的课上作业

时间:2015-11-09 20:51:49      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

动手动脑:运行 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();

   }

}

 

运行截图:

 技术分享

接口与继承的课上作业

标签:

原文地址:http://www.cnblogs.com/fan-xiaofan/p/4950900.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!