Home > Java > javaTutorial > body text

Detailed explanation of default access permission modifier of Java function

PHPz
Release: 2024-04-25 18:51:01
Original
988 people have browsed it

Java's default access modifier only allows classes in the same package to access functions, and it cannot be accessed by classes in other packages. Features include: 1. Can only be used for member functions in a class; 2. Access rights are lower than public and protected, but higher than private; 3. Cannot be used with other access rights modifiers at the same time.

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

Detailed explanation of default access permission modifier of Java function

In Java, we can use access permission modifiers to control the access permission of functions. Among them, the default modifier is a default access permission, which allows the function to be accessed by all classes in the same package, but not by classes in other packages.

Grammar

default void myFunction() {
    // 函数体
}
Copy after login

Practical case

We create a class named MyClass and define a default modification in it Function of symbol:

public class MyClass {

    default void myDefaultFunction() {
        System.out.println("这是 MyClass 中的默认函数。");
    }

}
Copy after login

In the OtherClass class in another package, we try to call the myDefaultFunction function:

public class OtherClass {

    public static void main(String[] args) {
        MyClass myClass = new MyClass();
        myClass.myDefaultFunction(); // 编译错误
    }

}
Copy after login

As shown above, The compiler will report an error because the myDefaultFunction function can only be accessed by classes in the same package, while OtherClass belongs to another package.

Note

When using the default access permission modifier, you need to pay attention to the following points:

  • default Modifiers can only be used on member functions in a class, not constructors or static functions. The
  • default modifier has lower access rights than public and protected, but higher access rights than private.
  • default modifier cannot be used with other access modifiers.

The above is the detailed content of Detailed explanation of default access permission modifier of Java function. For more information, please follow other related articles on the PHP Chinese website!

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