People said that we should provide accessor methods for attribute, and make the attribute private. I've been programming with Java for some time but still can't really understand the reason for that. Can someone help me?
hi Susilo Actually,a daily example can be used. If my things are public,such as money,house and chicken feet which I always use,so all the people can use my thing if they know my address or they see me.What are the problems? All the things can not be protected(secured),if I want to protect my (right of chicken feet) .So,the thing I do not want to share with other people that should be used private.And if other people want to use it,they should get the agreement with me and use the legal method (getter method) to get the license . So,some variables should be considered in which accessible modifier is used.It is related to design. hope this chicken feet help [ May 27, 2003: Message edited by: siu chung man ]
The reason we make properties private and supply accessor methods is so that we can control access to the properties. Imagine we have a property in our Employee class for annualSalary. If we make it public then anyone can change it to anything they like. A few months later we find that somehow annualSalary is sometimes being set to a negative value. So we decide to change the property to private and add an accessor. But everyone who has used our class will have to change their code!!! We will have made many enemies. Much better to use the accessor right from the start even if it does nothing except update the property without doing any checking.