zoukankan      html  css  js  c++  java
  • 接口与继承的课上作业

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

       }

    }

    运行截图:

     

  • 相关阅读:
    Spring Boot之@ImportResource、配置类、占位符表达式
    Spring Boot之测试类报错问题
    Spring Boot之@EnableAutoConfiguration源码解读
    Spring Boot之第一个程序及执行原理。
    eclipse中git使用中的冲突解决
    python画国旗
    第十六周进度
    个人课程总结
    人月神话之阅读笔记03
    第十五周进度
  • 原文地址:https://www.cnblogs.com/fan-xiaofan/p/4950900.html
Copyright © 2011-2022 走看看