Search code examples
javaconstructorgetter-setter

Getters and Setters and this. keyword


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!


Solution

  • In code examples I've found they only have a getter, but not a setter. But I don't really understand why.

    The functionality you describe is so when a Person object is created, nobody can set its gender and length. If a user wishes, he/she can create a new Person (new Person(...)) with attributes as they wish. But after a Person is created, you cannot set the attributes.

    But does the this.gender = gender work as a setter or not? I can't seem to find out what its function is.

    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 and length fields of a Person are not private then they can potentially be set/get outside of a set/get methods.