How to access private variables in Java?

In Java, private variables cannot be accessed directly from outside the class. However, they can be accessed indirectly through public access methods (getter and setter methods).

For example, let’s say there is a private variable named “name” that can be accessed through the following steps:

  1. Declare a private variable in a class.
private String name;
  1. Provide public access methods (getter and setter methods).
public String getName() {
    return name;
}

public void setName(String newName) {
    name = newName;
}
  1. Call the public access method from outside the class.
ClassName object = new ClassName();
object.setName("John"); // 调用setter方法设置私有变量的值
System.out.println(object.getName()); // 调用getter方法获取私有变量的值并打印输出

Through this method, it is possible to indirectly access and modify the values of private variables through a public access method.

bannerAds