Search code examples
javajavabeansgetter-setter

JavaBeans: how to have private data?


As per the JavaBeans specification, all member variables of a class must have public getter and setter methods. However, some data is logically part of the internal working of the class and should not be exposed to the user of a Bean. What is the correct way to have truly private data members?

One way I came up with was to have a private method, like getValueX(), which just returns the value X. Then, you can use this in place of the value of variable X. But this only allows retrieval, not update. What's the correct way to do it?


Solution

  • According to the original JavaBeans Spec:

    8.5 Design Patterns for Methods

    By default, we assume that all public methods of a Java Bean should be exposed as external methods within the component environment for access by other components or by scripting languages.

    Thus, it follows that if you have a class with fields that have only private accessors and mutators, they would be excluded from the introspection (by default) and that class can still technically represent a "Java Bean" since its properties with public accessors and mutators satisfy the JavaBeans specification.

    Having said that, I believe that it is better to access private fields directly in your implementation, rather than providing private setters and getters for them.