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() { // 函数体 }
UseFunctions modified by the private
modifier can only be accessed within the same class. This means:
Let us create a class namedPerson
and define aprivate
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 themain
method, we cannot directly access thegetAge()
function because it is declared asprivate
:
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 functionsetAge()
, 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!