Aniket Thakur
Aniket Thakur

Reputation: 68975

"Cannot reference Employee.DEFAULT_GENDER before supertype constructor has been called" Error

I have the following code

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

}

I am getting the following error

Cannot reference Employee.DEFAULT_GENDER before supertype constructor has been called

I don't understand why is it saying Employee.DEFAULT_GENDER? I have not defined it as static! and why is it not allowing me to call the constructor with 3 parameters? I have defined DEFAULT_GENDER and DEFAULT_AGE to ensure some default values. All you need to create an Employee object is his name(gender and age is set to default in that case. Also no default constructor allowed). Any views as of why this is happening?

Upvotes: 0

Views: 146

Answers (2)

Ran Adler
Ran Adler

Reputation: 3711

You can make it static if you want to be able to get it anywhere but used the first answer make a new instance as a better design

Upvotes: 0

AllTooSir
AllTooSir

Reputation: 49402

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.

Upvotes: 1

Related Questions