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();

       }

    }

    运行截图:

     

  • 相关阅读:
    什么叫TLD、gTLD、nTLD、ccTLD、iTLD 以及几者之间的关系
    socket
    windows下codeblocks报错undefined reference to `WSAStartup@8'|
    Codeforces 467C George and Job | DP
    51Nod 1049最大子段和 | 模板
    51Nod 最大子矩阵和 | DP
    AtomicInteger
    sun.misc.unsafe
    CAS
    java中的四种引用
  • 原文地址:https://www.cnblogs.com/fan-xiaofan/p/4950900.html
Copyright © 2011-2022 走看看