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

    }

    }

    运行结果截图:

  • 相关阅读:
    springboot缓存-Ehcache
    springboot+spring data jpa 多数据源配置
    vue+element 上传图片控件
    springboot下载文件
    easyPoi导入带图片的excel
    内外网同时使用(宽带内网无线内网)
    mysql 8.0 安装
    搭建一个Vue前端项目
    mybatis反向代理自动生成mapper文件
    【1】idea Live Templates
  • 原文地址:https://www.cnblogs.com/sunmei20142925/p/4942164.html
Copyright © 2011-2022 走看看