what is the use of getter and setter method? [duplicate]

给你一囗甜甜゛ 提交于 2019-12-05 18:16:06

The purpose is that you can always change the setter and the getter method with more sophisticated logic, if needed (for example validity check). If you don't use getter/setter you must write them and then change the code everywhere you change the field, which can lead to errors which will be very hard to find.

Having accessors and mutators hide the logic used to access that variable. IF the logic changes you only have to change it in the member function rather than everywhere that access that public variable. This helps keep the internal state data hidden from the outside world so you don't have to worry about the implementation details of those operations.

we use getter/setter and private data variables to ensure Data Encapsulation

well, you could make those accessors private. the client does not need to know the type's data representation -- this is a component of abstraction.

What I answerred is:

I agree that we can still declare variable 'i' as public and we can remove the usage of get/set methods. But This can only be done when you are 100% sure about that you're not going to change your class variable in future.

because...if we remove get/set methods, then we will be using 'i' directly in 100's of files.[like: object.i = 10;] And if by any chance, your variable 'i' changes to 'j', then your files will start failing.

So, to overcome this issue....we use get/set methods. and the only place you need to make change is within the class X, make 'i' --> 'j'.

That's the only use i could think of get/set methods.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!