Home >Java >javaTutorial >Rules for using access modifiers of Java functions in different classes
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.
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)
2. Package visibility (default)
3. protected access
4. Public access rights
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
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!