Cannot reference XXX before supertype constructor has been called

1.定义一个动物类,作为父类

public class Animal {
    private int id;
    private String name;
    private String desc;

    public Animal() {
    }

    public Animal(String name) {
        this.name = name;
    }

    public Animal(int id, String name, String desc) {
        this.id = id;
        this.name = name;
        this.desc = desc;
    }
}

2.创建子类

public class Goose extends Animal {

    private String name;
    private int age;
    private String desc = "jsk";


    public Goose(String name, int age) {
        super(name);
        this.age = age;
    }

    public Goose(int id, String name, int age) {
        super(id, name, desc);
        this.age = age;
    }

    @Override
    public void eat() {
        super.eat();
    }
}

发现一个错误,如下图示

原因:

非静态字段 desc 字段初始化了值,desc为Goose的实例变量,创建Goose对象时,会自动创建唯一一个desc实例,并将该实例附加在创建的对象上。但是父类构造函数会先初始化,此时作为父类构造函数的参数传入,会导致编译不通过

解决方法:

通过使变量为static ,它将与类本身相关联,而不是该类的实例,并在Test所有实例之间共享。 当JVM首次加载类时,将创建静态变量。 由于在使用它来创建一个实例时,类已经被加载,所以静态变量可以使用,因此可以在类中使用,包括构造函数

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值