Wednesday, July 5, 2017

Java constructor parameter (or local variable) has the same name as a field in the same class

A Java constructor parameter can have the same name as a field. If a constructor parameter has the same name as a field, the Java compiler has problems knowing which you refer to. By default, if a parameter (or local variable) has the same name as a field in the same class, the parameter (or local variable) "shadows"(override) for the field. Look at this constructor example:
public class Employee {

    private String firstName = null;
    private String lastName  = null;
    private int    birthYear = 0;


    public Employee(String firstName,
        String lastName,
        int    birthYear ) {

        firstName = firstName;
        lastName  = lastName;
        birthYear = birthYear;
    }
    
}
Inside the constructor of the Employee class the firstName, lastName and birthYear identifiers now refer to the constructor parameters, not to the Employee fields with the same names. Thus, the constructor now just sets the parameters equal to themselves. The Employee fields are never initialized.
To signal to the Java compiler that you mean the fields of the Employee class and not the parameters, put the this keyword and a dot in front of the field name. Here is how the Java constructor declaration from before looks with that change:
public class Employee {

    private String firstName = null;
    private String lastName  = null;
    private int    birthYear = 0;


    public Employee(String firstName,
        String lastName,
        int    birthYear ) {

        this.firstName = firstName;
        this.lastName  = lastName;
        this.birthYear = birthYear;
    }
    
}
 
@reference_1_jenkov.com
Java Constructors

No comments:

Post a Comment