Home >Java >javaTutorial >Rules for using access modifiers of Java functions in different classes

Rules for using access modifiers of Java functions in different classes

PHPz
PHPzOriginal
2024-04-25 13:54:02862browse

When using Java functions in different classes, follow the following access rights rules: Default access rights are limited to classes within the same package. Package visibility is the same as default access, but applies to all classes in the same module. Protected access is limited to subclasses and classes in the same package. Public access rights are visible in all classes.

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

The rules for using access permission modifiers in Java functions in different classes

The access permission modifiers in Java use Used to control the visibility scope of classes, methods, and fields. When using functions in different classes, you need to abide by the following rules:

1. Default access permissions (no modifiers)

  • Only within the same package Visible in class

2. Package visibility (default)

  • Same as default access, but applies to all classes in the same module

3. protected access

  • Visible only in subclasses of this class and classes in the same package

4. Public access rights

  • Visible in all classes

Practical case

Consider the following code:

// MySuperClass.java
public class MySuperClass {
    protected void protectedMethod() {
        // ...
    }

    public void publicMethod() {
        // ...
    }
}
// MySubClass.java
public class MySubClass extends MySuperClass {
    // 可访问父类的 protected 和 public 方法
    void accessProtected() {
        protectedMethod();
    }

    void accessPublic() {
        publicMethod();
    }
}
// MyOtherClass.java
public class MyOtherClass {
    // 无法访问父类的 protected 或 public 方法
    void accessProtected() {
        // 编译错误: protectedMethod() 具有 protected 访问权限,在此包外不可访问
    }

    void accessPublic() {
        // 编译错误: publicMethod() 具有 public 访问权限,但在不同的模块中不可访问
    }
}

In this example, MyOtherClass cannot access protectedMethod() and publicMethod( in MySuperClass ) because they are not in the same package or are not subclasses of MySuperClass.

Notes

  • Inner classes can access all members of their outer classes, regardless of access modifiers.
  • The compiler will check the access permissions, and if the rules are violated, a compilation error will be generated.

The above is the detailed content of Rules for using access modifiers of Java functions in different classes. 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