I donโt know of any rule that says that any particular attribute should be private in the class, Java offers other modifiers, such as protected and public, and no modifier that implies the availability of the package. All of them are there, so you can apply different levels of encapsulation , which you can consider suitable in accordance with your design.
Regarding the initialization of the question field, I believe that when the field is declared in the class, if the field has any reference type it is default initialized to null , so you do not need to initialize it if you do not consider it necessary, or if the field is not declared final, which means you want to initialize it to its default value.
On the question of how to get and establish part of the question, I believe that this is just a way to provide encapsulation. Allan Snyder, in his article Encapsulation and Inheritance in Object-Oriented Programming Languages, wrote:
To maximize the benefits of encapsulation, you should minimize the identification of implementation details in external interfaces [...] For example, one characteristic of an object-oriented language is whether it allows a designer to define a class so that its instance variables can be renamed without affecting clients.
Also, a great article by Leonid Mikhailov and Emil Sekerinsky described the study of the fragile base class problem may show some good ideas on why all these levels of encapsulation and indirection are appropriate to avoid some of the classic inheritance problems.
โThere is no direct access to the state of the base classโ: the extension of the class should not directly access the state of its base class, but only by calling methods of the base class.
Their article provides very good reasons why something like the getter and setter methods might be a good idea to avoid class vulnerabilities.
source share