Home > Java > javaTutorial > Detailed explanation of private access modifiers for Java functions

Detailed explanation of private access modifiers for Java functions

WBOY
Release: 2024-04-25 16:48:01
Original
377 people have browsed it

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.

Java 函数的访问权限修饰符之 private 详解

Detailed explanation of private access modifier of Java function

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.

Syntax

private The modifier is applied before the function declaration, the syntax is as follows:

private void functionName() {
    // 函数体
}
Copy after login

Access rules

Use Functions modified by the private modifier can only be accessed within the same class. This means:

  • The function cannot be accessed from other classes.
  • This function cannot be accessed from subclasses.

Practical case

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;
    }
}
Copy after login

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();
    }
}
Copy after login

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 函数获取年龄
    }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template