When using Java functions in different packages, the access rights rules are: 1. public: visible to all packages; 2. protected: visible to the current package and subclasses; 3. default: visible only to the current package; 4. private: only visible within the same class. Practical example: Only public functions can be called in other packages, but private functions cannot be called.
Rules for using access modifiers of Java functions in different packages
The access modifiers of Java functions determine The accessibility of functions. When using functions in different packages, you need to follow specific rules:
Practical example:
We define a class named MyClass
, which contains two functions: publicMethod ()
and privateMethod()
:
public class MyClass { public void publicMethod() { System.out.println("Public method"); } private void privateMethod() { System.out.println("Private method"); } }
In other packages OtherClass.java
:
import MyClass; public class OtherClass { public static void main(String[] args) { MyClass myClass = new MyClass(); myClass.publicMethod(); // 可调用 //myClass.privateMethod(); // 报错,不可调用 } }
In classes nested in other packages, NestedClass.java
:
import MyClass; public class OuterClass { public static class NestedClass { public static void main(String[] args) { MyClass myClass = new MyClass(); myClass.publicMethod(); // 可调用 //myClass.privateMethod(); // 报错,不可调用 } } }
As shown in the example, in other packages, only those with public
Functions with access rights can be accessed.
The above is the detailed content of Rules for using access modifiers of Java functions in different packages. For more information, please follow other related articles on the PHP Chinese website!