|
Re: Constructor, setters and getters
|
Posted: May 4, 2009 11:43 PM
|
|
> Ok, I am an green Java programmer in a Java class for > college (online) I am having trouble getting my instructor > to respond to my questions so I figure that I will ask > them here. > > If we initialize variables via a constructor such > such as: > > private String firstName > private String lastName > > public employee (String first, String last) > > > Why do we include setter methods that initialize the > e the string parameters "first" and "last" to "firstName" > and "lastName"? > > Why do we not just initialize these variables via the > a the constructor with the same variable names("firstName" > and "lastName" instead of "first" and "last") in the > first place? > > Would the constructor not assign these values to the > correct variables anyways so we could just skip the > "setter" methods and go straight to creating "getter" > methods to access these variable values?
You can initialize the variables via a Constructor, but in the case of Getters and Setters they are really accessor methods to your object. You could still access your variables via reflection (but that's a different path for frameworky stuff).
Employee emp = new Empoyee("Someone", "Surname");
// now firstName = "Someone" and lastName = "Surname"
Now say the last name has changed, do you really want to go and instantiate emp again?
emp.setLastName("NewMarriedName");
|
|