zoukankan      html  css  js  c++  java
  • 07继承与接口

    1、运行TextInherists.java 示例,观察输出,注意总结父类与子类之间构造方法的的调用关系,修改parent构造方法的代码,显式调用grandparent另一个构造函数。

    源代码:

    class GrandParent{
    public GrandParent(){
    System.out.println("GrandParent Created");
    }

    public GrandParent(String string){
    System.out.println("GrandParent Created"+string);
    }
    }
    class Parent extends GrandParent{
    public Parent(){
    super("123");//调用父类有参数的构造函数
    System.out.println("Parent Created");
    }
    }
    class Child extends Parent{
    public static void main(String[] args){
    Child c=new Child();
    }

    public Child(){
    System.out.println("Child Created");
    }
    }

    运行结果截图:

    修改后的截图:

    通过super()调用父类构造方法,必须在子类构造方法的第一句。

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

    构造函数的作用是初始化对象,类继承了父类,就默认含有父类的公共成员方法和公共成员变量,这些不再子类中重复声明。而构造方法则相当于把父类给实例化出来,

    如果子类实例化的时候不调用父类的构造方法,相当于子类压根就没有父亲。不能反过来。

  • 相关阅读:
    华为软件开发云评测
    个人技术博客(α)
    结对第二次作业
    结对第一次作业----部门通
    数独设计
    2017软件工程实践第一次作业
    Alpha冲刺博客集
    个人作业——软件工程实践总结作业
    用户使用调查报告
    总结随笔(Beta)
  • 原文地址:https://www.cnblogs.com/shouhutian/p/6055961.html
Copyright © 2011-2022 走看看