+ 3
Need of getters and setters
I donât get why we need to have a separate unique function for get and set when you can do the same by just declaring your own function?
1 Answer
+ 5
As for the need, it's called encapsulation. You're hiding the members of the class from the rest of your code, which adds better security around the class and the objects created from it. The get/set methods are what allows us to still be able to manipulate those hidden (private) members and do what we need to do with it, all while maintaining keeping them hidden. Otherwise, you wouldn't be able to access those private members on the objects that you create from that class.
For all of the various get methods, they'll have a different return types depending upon the data type of the private members being retrieved. As such, you couldn't really combine ALL of the get methods into a single get method, presumably because they may not all be the same data type. As well, depending upon the amount of private members you're dealing with, combining all of them into a single function gets messy quick and you'll have to do a lot of code dealing with validation and ensuring that you don't accidentally manipulate the wrong members. So keeping them separate, and each having their own respective getName/setName, makes it a lot easier for you to deal with in your code and makes it a lot more readable.
Imagine that you tried to create a single function for all of your setters:
public void setAll(String firstName, String, lastName, int age, int addressNum, String city, String state, double GPA, int SSN, String role) {
// a WHOLE bunch of code to figure out what you're even wanting to do, validating stuff, and ensuring that you do nothing at all to change the wrong private members, etc.... It's messy, unclear, and a PAIN to deal with later when you're working with your objects.
}
Now imagine you want to use that new function to change ONLY the city and address because they moved. You would have to specify ALL of the arguments. If you set up defaults, it'll change them to defaults when you want to just change one thing. To write a LOT more code to keep it in one function rather than having each individual get/set.