Home> Java> javaTutorial> body text

Detailed explanation of default access permission modifier of Java function

PHPz
Release: 2024-04-25 18:51:01
Original
921 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, thedefaultmodifier 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 namedMyClassand define adefaultmodification in it Function of symbol:

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

In theOtherClassclass in another package, we try to call themyDefaultFunctionfunction:

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 themyDefaultFunctionfunction can only be accessed by classes in the same package, whileOtherClassbelongs to another package.

Note

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

  • defaultModifiers can only be used on member functions in a class, not constructors or static functions. The
  • defaultmodifier has lower access rights thanpublicandprotected, but higher access rights thanprivate.
  • defaultmodifier 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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!