zoukankan      html  css  js  c++  java
  • 10.21 继承与多态动手动脑

    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 调用基类构造方法,必须是子类构造方法中的第一个语句。

    2.

    参看ExplorationJDKSource.java示例 此示例中定义了一个类A,它没有任何成员: class A { } 示例直接输出这个类所创建的对象 public static void main(String[] args) { System.out.println(new A()); }

    我们得到了一个奇特的运行结果: A@1c5f743

    package dongshou;

    public class ExplorationJDKSource {

    /**
    * @param args
    */
    public static void main(String[] args) {
    System.out.println(new A());
    }

    }

    class A{}

    反编译的结果为

    3.

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

    package dongshou;


    class Parent
    {


    public Parent()
    {

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

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

    // super("Hello.Grandparent.");
    }
    void ok()
    {
    System.out.println("a");
    }

    }

    class Child extends Parent
    {

    public Child()
    {
    super();
    System.out.println("Child Created");
    }
    void ok()
    {
    super.ok();
    System.out.println("b");
    }
    }

    public class TestInherits
    {


    public static void main(String args[])
    {

    Child c = new Child();
    c.ok();
    }

    }

    运行结果

    Parent Created
    Child Created

    a

    b

  • 相关阅读:
    08-图9 关键活动 (30 分)
    08-图8 How Long Does It Take (25 分)
    08-图7 公路村村通 (30 分)
    07-图6 旅游规划 (25 分)
    07-图5 Saving James Bond
    使用RichTextBox控件保存文件
    在RichTextBox控件中显示RTF格式文件
    在RichTextBox控件中插入图片
    在RichTextBox控件中添加超链接文本
    实现带查询功能的ComboBox控件
  • 原文地址:https://www.cnblogs.com/2940500426yingxin/p/11729262.html
Copyright © 2011-2022 走看看