zoukankan      html  css  js  c++  java
  • 07课堂问题整理

    作业归档7 继承与接口

    完成课件中的动手动脑的或需要验证的相关内容。

    1、运行 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();

        }

    }

    运行结果:

    GrandParent Created.

    Parent Created

    Child Created

    当把第一个//super("Hello.Grandparent.");//去掉后,运行结果是

    GrandParent Created.String:Hello.Grandparent.

    Parent Created

    Child Created

    说明super可以调用父类的构造方法。

    若是把第二个//super("Hello.Grandparent.");//去掉后,将会出现编译错误Constructor call must be the first statement in a constructor说明要用super调用父类构造方法,必须是在子类构造方法中的第一句。

    为什么子类的构造方法在运行之前,必须调用父类的构造方法?

    子类是通过父类继承过来的,所以子类有父类的属性和方法,如果不调用父类的构造方法,无法初始化父类中定义的属性,无法给父类的属性分配内存空间。

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

    public class YanZheng {

        public static void main(String []args){

         Pear pear=new Pear();

         pear.output();

        }

    }

    class Apple{

    public void output(){

    System.out.println("父类:苹果。");

    }

    }

    class Pear extends Apple{

    public void output(){

    super.output();

    System.out.println("子类:梨。");

    }

    }

    运行结果:

    父类:苹果。

    子类:梨。

  • 相关阅读:
    不同品牌交换机设置telnet方法
    Oracle 11G RAC For Windows 2008 R2部署手册(亲测,成功实施多次)
    oracle 11g ADG实施手册(亲测,已成功部署多次)
    如何正确的使用uwsgi
    debian小巧好看的桌面
    zsh中home键失灵问题
    C#_Markov_心得感想
    NLP—WordNet——词与词之间的最小距离
    这不算爬虫吧?!
    Table-Driven Design 表驱动设计
  • 原文地址:https://www.cnblogs.com/hjy415/p/6055459.html
Copyright © 2011-2022 走看看