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