• 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、为什么子类的构造方法在运行之前,必须调用父类的构造方法?能不能反过来?为什么不能反过来?

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

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

    3、在子类中,如果调用父类被覆盖的方法,可以使用super关键字。

    class Friut{
    public void  show(){
    System.out.println("Fruit!");
    }
    }
    class Apple extends Friut{
    
    public void show(){
    System.out.println("Apple!");
    super.show();
    }
    }
    
    public class fangFaSuper{
    public static void main(String[] args){
    Apple a=new Apple();
    a.show();
    }
    }

    运行结果截图:

  • 相关阅读:
    2020软件工程作业04
    2020软件工程作业02
    2020软件工程作业01
    2020软件工程个人作业06——软件工程实践总结作业
    【软件工程小组-冲刺日志(第二天)】
    软件工程逃课小组 【团队名称-凡事预则立】
    2020软件工程作业——团队02
    2020软件工程作业05
    2020软件工程作业00——问题清单
    2020软件工程作业04
  • 原文地址:https://www.cnblogs.com/jingxiaopu/p/6049076.html
Copyright © 2020-2023  润新知