• 第七次课后作业


    第七次课后作业

    1505-1

    20153122

    马建宁

    动手动脑:

    题目:在子类中,若要调用父类中被覆盖的方法,可以使用super关键字。

    测试代码:package 实验七;

     

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

        }

     

    }

    不加super运行结果:

    加super:

    所以若要调用父类中被覆盖的方法,可以使用super关键字。

    实验二:

    内容:继承条件下构造方法的调用。运行 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();

        }

     

    }

    结论:通过 super 调用基类构造方法,必须是子类构造方法中的第一个语句。

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

        构造函数(constructor)是一种特殊的方法 。主要用来在创建对象时初始化对象, 即为对象成员变量赋初始值,总与new运算符一起使用在创建对象的语句中 。特别的一个类可以有多个构造函数 ,可根据其参数个数的不同或参数类型的不同来区分它们 即构造函数的重载。构造函数的功能主要用于在类的对象创建时定义初始化的状态。
       所以说构造函数的作用,简单来说就是初始化,初始化一个新建的对象
  • 相关阅读:
    MapReduce实例
    hadoop 分布式安装
    redis缓存
    Flink初始
    Flume初始
    大数据学习之路(持续更新中...)
    使用VisualVM分析性能
    JVM的理解
    Java日记
    UI笔记2
  • 原文地址:https://www.cnblogs.com/ever1961211/p/6055381.html
Copyright © 2020-2023  润新知