Can we use getters without using setters & vice-versa?
Vinay
Level 11
Getters and Setters
Resolved
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
9 March 2021, 15:17solution
They are only methods, nothing special above that. You can name them differently if you want, and you can make them do additional things if you want (within the normal rules of any methods). The reasons to use get/set is for conformity/standardization. Programming is already hard to learn in the first place. Imagine a million programmers all naming their get/set methods something completely different. Every library you use, and you will use a lot, you would have to figure it out from scratch. This was actually a big problem at one point (50+ years ago) with the initialize() method. That is why constructors were invented, they standardized that and made it easier for everyone.
Also, in object orientated programming, abstraction (hiding information not important) is one of the key tenants. The get/set methods are commonly used to hide, and protect, the class variables from users of the class.
Take this as an example, lets say you had a class with a single fields, an int called "numberBetween0And9", that is supposed to only be a value between 0 and 9. Anything outside that would break the code in the class. You would make that private so users of the class couldn't access it directly, then in the set method you would first check the int passed in as an argument to ensure its within the range before setting the field; or if it was outside the range to either throw an exception or set it to a default value.
Now you have used OOP techniques to protect your class from inadvertent bad data. +2
Vinay
9 March 2021, 16:22
As always, crystal clear explanation.
Thank you Guadalupe
0