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

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

    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 Test{

        public static void main(String args[]) {

            Child c = new Child();

        }

    }

    运行结果截图:

    思考:

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

    构造一个对象,先调用其构造方法,来初始化其成员函数和成员变量。子类拥有父的成员变量和成员方法,如果不调用,则从父类继承而来的成员变量和成员方法得不到正确的初始化。

    不能反过来。

    2

    源程序代码:

    public class Test {

    /**

     * @param args

     */

    public static void main(String[] args) {

    System.out.println(new A());

    }

    }

    class A{}

    运行结果截图:

     

    源程序代码:

    public class Fruit

    {

    public String toString()

    {

    return "Fruit toString.";

    }

    public static void main(String args[])

    {

    Fruit f=new Fruit();

    System.out.println("f="+f);

    // System.out.println("f="+f.toString());

    }

    }

    运行结果截图:

  • 相关阅读:
    Mybatis连接配置文件详解
    MyBatis映射配置文件详解
    AGC 016 C
    CodeForces
    UVA
    某5道CF水题
    DZY Loves Chinese / DZY Loves Chinese II
    [SHOI2016] 黑暗前的幻想乡
    CodeForces
    CodeForces
  • 原文地址:https://www.cnblogs.com/sunmei20142925/p/4942164.html
Copyright © 2011-2022 走看看