I'm new to coding and I'm confused about getters and setters in Java. I know that getters and setters are used for encapsulation. But if you have a constructor that creates a person of a specific gender and length. Should both of these characteristics have a setter and a getter?
public Person(Gender gender, Length length) {
this.gender = gender;
this.length = length;
}
Does the this.gender serve as a setter? If no, what's its function?
Do I need to make a getter and setter for these? In code examples i've found they only have a getter, but not a setter. But i don't really understand why. Thanks in advance!
The functionality you describe is so when a
Personobject is created, nobody cansetitsgenderandlength. If a user wishes, he/she can create a newPerson(new Person(...)) with attributes as they wish. But after aPersonis created, you cannotsetthe attributes.It does work as a setter (though not a setter by itself since it's not a function). But only within the constructor. As I said above.
Note that if the
genderandlengthfields of aPersonare notprivatethen they can potentially beset/getoutside of a set/get methods.