How to define private variables in Java?

In Java, you can use the keyword “private” to define private variables. These variables can only be accessed within the class they belong to and cannot be accessed directly by other classes. The way to define private variables is as follows:

private 数据类型 变量名;

For example, defining a private integer variable called age:

private int age;

Private variables typically have public getter and setter methods to access and modify their values. For example, for the private variable ‘age’ mentioned above:

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

By calling the getAge() method, you can retrieve the value of age, and by calling the setAge() method, you can set the value of age. This allows for encapsulating private variables and controlling access to and modification of the variables.

bannerAds