0

我有以下代码

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 对象所需的只是他的姓名(在这种情况下,性别和年龄设置为默认值。也不允许使用默认构造函数)。关于为什么会发生这种情况的任何观点?

4

2 回答 2

1

DEFAULT_GENDER is an instance variable of the class Employee, it cannot be used until an instance of the class is created. Until the constructor executes completely the instance is not fully constructed, hence you get such an error.

Make both the default values as static .

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

Qualifying the variables as static makes them associated with the class Employee and hence it can exist without creating any instance of the class Employee.

于 2013-07-31T05:48:53.503 回答
0

如果您希望能够在任何地方获得它,则可以将其设为静态,但使用第一个答案创建一个新实例作为更好的设计

于 2013-07-31T05:54:58.030 回答