构造方法中super()的作用 您所在的位置:网站首页 super方法和this方法有什么区别 构造方法中super()的作用

构造方法中super()的作用

2023-12-03 04:55| 来源: 网络整理| 查看: 265

在类的继承中,子类的构造方法中默认会有super()语句存在,相当于执行父类的相应构造方法中的语句 如下面代码:

class Extends_Demo { public static void main(String[] args) { Cat c = new Cat(); //---------------(1) System.out.println("-------------------"); Cat c1 = new Cat("花花",4); //----------------(2) } } class Animal { private String color; private int foot; public Animal(){ System.out.println("我是父类无参数构造器"); } public Animal(String color,int foot){ System.out.println("我是父类有参数构造器"); this.color = color; this.foot = foot; } } class Cat extends Animal{ public Cat(){ super(); //---------------可以省略 System.out.println("我是子类无参数构造器"); } public Cat(String color,int foot){ //super(color,foot); //---------------(3) super(); //---------------可以省略 System.out.println("我是子类有参数构造器"); } }

输出 这里写图片描述 main方法中 (1)语句执行的是子类的无参数构造方法,内部默认有super(),代表执行父类无参数构造方法,因此输出父类无参数构造方法中的语句和子类无参数构造方法中的语句; (2)语句执行的是子类有参数构造方法,内部也是默认有super(),代表执行父类无参数构造方法,,输出语句是父类无参数构造方法中的语句和子类有参数构造方法中的语句; 若将(3)语句解除屏蔽,则子类有参构造方法中执行super(color,foot)表示执行父类有参构造方法Animal(color,foot),修改后子类:

class Cat extends Animal{ public Cat(){ super(); //----------------可以省略 System.out.println("我是子类无参数构造器"); } public Cat(String color,int foot){ super(color,foot); //---------------(3) //super(); System.out.println("我是子类有参数构造器"); } }

输出 这里写图片描述 对比后可以知道,super()代表执行父类无参数构造方法内容,super(color,foot)代表执行父类有参数构造方法。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有