Home >Java >javaTutorial >Detailed explanation of default access permission modifier of Java function
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, 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.
default void myFunction() { // 函数体 }
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 中的默认函数。"); } }
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(); // 编译错误 } }
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.
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!