private is a Java access modifier that restricts the accessibility of a function to only the class in which it is defined, including: the function cannot be accessed in other classes. The function is also not accessible in subclasses.
In Java, private
is an access modifier. It is used to limit the accessibility of functions. It is the most restrictive access modifier, allowing access to the function only within the class in which it is defined.
private
The modifier is applied before the function declaration, the syntax is as follows:
private void functionName() { // 函数体 }
Use Functions modified by the private
modifier can only be accessed within the same class. This means:
Let us create a class named Person
and define a private
function in it to get the age:
class Person { private int age; public void setAge(int age) { this.age = age; } // `private` 函数只能在这个类中访问 private int getAge() { return age; } }
In the main
method, we cannot directly access the getAge()
function because it is declared as private
:
public class Main { public static void main(String[] args) { Person person = new Person(); person.setAge(25); // 编译器错误:getAge() 函数是私有的 // int age = person.getAge(); } }
In order to get the age, we need to set the age through the public function setAge()
, and then use the getter function to get the age:
public class Main { public static void main(String[] args) { Person person = new Person(); person.setAge(25); int age = person.getAge(); // 通过 getter 函数获取年龄 } }
The above is the detailed content of Detailed explanation of private access modifiers for Java functions. For more information, please follow other related articles on the PHP Chinese website!