This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
In java to implement encapulations, all variables are declared private and methods those set and get value of particular variables are declared public. So that all other are not able to access that variables directly.
I hope you understand....
Joined: Jul 24, 2008
I don't understand why it is unsafe for the member to be accessed directly..
Getters and setters allow additional functionality to be included--as a trivial example think of lazy instantiation of expensive properties. By encapsulating property access behind methods no code needs to change if, say, a publicly-accessible property now needs additional functionality provided by a getter/setter method.
They also allow trivial discovery by tools of properties *meant* to be accessible (by looking for methods prefixed with get/set).
Derek White wrote:I don't understand why it is unsafe for the member to be accessed directly..
Is there some documentation for this?
It's not always unsafe and will depend on your implementation. There's the camp that believes that business logic belongs within the JavaBean. If that is the case, often times when setting or getting a property, business rules must be applied to them first. So there is additional logic in these mutator methods to achieve this. The other reason getters/setters are fairly common is because of libraries that work off JavaBeans and reflection like Hibernate, for example. Hibernate requires getters and setters for every persistent property of the object to work. This is also true many other libraries out in the java world.
There is actually quite a bit of debate regarding private/public variables and mutator methods. Googling and searching this site will provide more information. Unfortunately there isn't really a best practice. More often than not you are going to find yourself requiring getters/setters for various reasons.
Derek White wrote:Additional functionality? As in restrictions and such?
Or maybe to fire an event when the String in question is changed?
Yep. You got it. Also note that is can also depend on what you are developing for. When designing a system where a lot of people will be using it and programming against your API it is really important to restrict access and control access to important data. Whether that restriction rests solely on the objects themselves or are proxied through other objects is up to you. But if you need to be concerned about how a property is set (and at times retrieved) from an object, you need to control that via methods, and not expose the variables directly.