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.
In Java, we can use access permission modifiers to control the access permission of functions. Among them, thedefault
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.
default void myFunction() { // 函数体 }
We create a class namedMyClass
and define adefault
modification in it Function of symbol:
public class MyClass { default void myDefaultFunction() { System.out.println("这是 MyClass 中的默认函数。"); } }
In theOtherClass
class in another package, we try to call themyDefaultFunction
function:
public class OtherClass { public static void main(String[] args) { MyClass myClass = new MyClass(); myClass.myDefaultFunction(); // 编译错误 } }
As shown above, The compiler will report an error because themyDefaultFunction
function can only be accessed by classes in the same package, whileOtherClass
belongs to another package.
When using thedefault
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. Thedefault
modifier has lower access rights thanpublic
andprotected
, but higher access rights thanprivate
.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!