By setting the property to private, you can avoid external direct access and modification of the internal state of the object, and you can only access and modify the property indirectly through the public * * * method. This can effectively control the access rights of attributes and avoid the confusion of object state caused by unreasonable operation.
In addition, setting the property to private can provide better encapsulation. The internal implementation details of the object are transparent to the outside, and the outside can only interact with the object through public methods. This can reduce the direct dependence on attributes and improve the flexibility and scalability of the code.
Extended content: For private property access, you can indirectly access and modify the property through public Getter and Setter methods. The Getter method is used to get the value of the property, and the Setter method is used to set the value of the property. In this way, we can control and verify the access of attributes while ensuring encapsulation, and ensure the legitimacy of attribute values.
In addition, you can also use other access modifiers, such as protected or package-level private access modifiers (the default), and choose the appropriate modifiers according to specific requirements and design specifications. But generally speaking, private attribute is the strictest access control level, which can protect the internal state of the object to the greatest extent.