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

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

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

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

    运行结果截图:

  • 相关阅读:
    Plot the figure of K-SVCR
    利用sklearn计算文本相似性
    djago 定义后台地址
    django admim后台不转义提交的html
    django 静态css js文件配置
    django后台的制作
    django 设置不带后缀的访问路径
    阿里云ECS服务器 常见问题(1)
    python 将word另存为txt
    python遍历某一位置所有文件夹中的文件
  • 原文地址:https://www.cnblogs.com/jingxiaopu/p/6049076.html
Copyright © 2011-2022 走看看