In Java,
Do objects encapsulate data so that not even other instances of the same class can access the data? Only when the keyword \"private\" is used? What are \"ac
What are "accessor methods" in Java - methods like getName()?
Yes - getFoo()
and setFoo()
are accessor methods for a "property" named foo
- this is part of the JavaBeans specification. The reason why these are preferred over public fields is that they allow you to have only a getter (making the property read only), do additional bookkeeping (like calculating derived fields) and validation of set values (throwing e.g. a PropertyVetoException when the value is not acceptable).
The whole thing was originally intended to be used with GUI tools that would allow you to graphically configure and combine JavaBeans in order to "build applications". This turned out to be largely a pipe dream, but the concept of JavaBeans and properties has turned out to be useful for regular coding and become wide-spread.
Many people misunderstand the concept and believe that "encapsulation" just means writing setters and getters for private properties instead of making them public - and then rightfully consider that idiotic. Encapsulation means not exposing the inner workings of a class at all except in tightly controlled ways. In good OO design, you should not have too many get methods and very few set methods in a class.