Home  >  Article  >  Java  >  Rules for using access modifiers of Java functions in different packages

Rules for using access modifiers of Java functions in different packages

WBOY
WBOYOriginal
2024-04-25 17:42:011079browse

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.

Java 函数的访问权限修饰符之在不同包中使用的规则

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:

  • public: Visible to all packages, including the current package and other packages.
  • protected: Visible to the current package and subclasses.
  • default (no modifier): Visible only to the current package.
  • private: Only visible within the same class.

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!

Statement:
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