gpt4 book ai didi

java - "Cannot reference Employee.DEFAULT_GENDER before supertype constructor has been called"错误

转载 作者:行者123 更新时间:2023-12-01 14:17:42 27 4
gpt4 key购买 nike

我有以下代码

public class Employee {

private String name;
private String gender;
private int age;

final String DEFAULT_GENDER = "male";
final int DEFAULT_AGE = 18;

public Employee(String name,String gender,int age) {
this.name = name;
this.gender = gender;
this.age = age;
}

public Employee(String name) {
this(name,DEFAULT_GENDER,DEFAULT_AGE);
}

}

我收到以下错误

Cannot reference Employee.DEFAULT_GENDER before supertype constructor has been called

我不明白为什么显示为Employee.DEFAULT_GENDER?我没有将其定义为静态!为什么它不允许我调用带有 3 个参数的构造函数?我定义了 DEFAULT_GENDERDEFAULT_AGE 以确保一些默认值。创建 Employee 对象所需的只是他的名字(在这种情况下,性别和年龄设置为默认值。也不允许使用默认构造函数)。对于为什么会发生这种情况有什么看法吗?

最佳答案

DEFAULT_GENDEREmployee 类的实例变量,在创建该类的实例之前无法使用它。在构造函数完全执行之前,实例尚未完全构造,因此会出现这样的错误。

将两个默认值设置为 static

final static String DEFAULT_GENDER = "male";
final static int DEFAULT_AGE = 18;

将变量限定为static 使它们与Employee 类关联,因此它可以在不创建Employee 类的任何实例的情况下存在。

关于java - "Cannot reference Employee.DEFAULT_GENDER before supertype constructor has been called"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17962496/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com