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
Person
object is created, nobody canset
itsgender
andlength
. If a user wishes, he/she can create a newPerson
(new Person(...)
) with attributes as they wish. But after aPerson
is created, you cannotset
the 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
gender
andlength
fields of aPerson
are notprivate
then they can potentially beset
/get
outside of a set/get methods.