When to declare member variables when public and when to use private?

In Java, member variables (properties of a class) can be declared with different access modifiers, including public and private.
The following are general guidelines for using public and private:

1. Public member variable:
   - When you want the member variable to be directly accessible outside the class, you can declare it as public.
   - Public member variables can be directly accessed and modified by instances of the class and other classes.

2. Private member variables:
   - When you want to restrict direct access to member variables and control access and modification through class methods, you can declare them as private.
   - Private member variables can only be accessed and modified inside the class, and cannot be directly accessed from outside the class.

By declaring member variables as private, the concept of encapsulation (Encapsulation) can be realized, which is one of the important principles of object-oriented programming.
Encapsulation hides the internal implementation details of a class, provides controlled access to the class, and ensures data security and consistency.

In general, it is recommended to declare class member variables as private, and access and modify these variables through public getter and setter methods.
This maintains the encapsulation of the class, providing greater control and flexibility without directly exposing internal implementation details.

For example, consider the following example:

```java
public class Person {     private String name; // private member variable

    public String getName() {         return name; // public getter method     }

    public void setName(String newName) {         name = newName; // public setter method     } } ```



In the above example, the name member variable is declared private to prevent direct access.
Through the public getter method `getName()` and setter method `setName()`, the value of name can be safely accessed and modified outside the class.

It is important to note that these are general guidelines only and specific circumstances may vary.
According to requirements and design goals, sometimes you may need to declare member variables as public,
but in most cases, try to use private to maintain encapsulation and data security.

Guess you like

Origin blog.csdn.net/qq_20936333/article/details/131444850