Java function access permission modifiers include: public, protected, default and private. The following precautions need to be followed: Nested classes can only access private members of external classes; functions in subclasses inherit the access permissions of the parent class, but cannot reduce them; under polymorphism, when subclasses override parent class functions, access permissions cannot be more restrictive. The ;default modifier makes the function visible only within the same package.
Access modifiers for Java functions: Precautions when using them
Preface
Access modifiers are used to control the visibility of Java functions to other classes or packages, which is crucial to ensuring the encapsulation and security of the code. This article will introduce the precautions for using function access permission modifiers in Java and illustrate them through practical cases.
Access permission modifiers
Commonly used function access permission modifiers in Java include:
Notes
When using the access permission modifier, you need to follow the following precautions:
Practical case
Demonstrates a code example containing two classes to illustrate the use of access permission modifiers:
// 外部类 public class OuterClass { private int privateField; // 私有字段 protected int protectedField; // 受保护字段 int defaultField; // 默认字段 public int publicField; // 公共字段 // 私有方法 private void privateMethod() { System.out.println("私有方法"); } // 受保护方法 protected void protectedMethod() { System.out.println("受保护方法"); } // 默认方法 void defaultMethod() { System.out.println("默认方法"); } // 公共方法 public void publicMethod() { System.out.println("公共方法"); } } // 内部类 class InnerClass { public static void main(String[] args) { OuterClass outer = new OuterClass(); // 访问内部类中的公共字段 System.out.println(outer.publicField); // 访问外部类中的默认字段(因为内部类和外部类在同一包中) System.out.println(outer.defaultField); // 无法访问外部类中的私有字段 // System.out.println(outer.privateField); // 无法访问外部类中的受保护字段(因为内部类不是外部类的子类) // System.out.println(outer.protectedField); // 无法调用外部类中的私有方法 // outer.privateMethod(); // 可以调用外部类中的受保护方法 outer.protectedMethod(); // 可以调用外部类中的默认方法 outer.defaultMethod(); // 可以调用外部类中的公共方法 outer.publicMethod(); } }
In this In the example:
privateField
OuterClass
can only be accessed in OuterClass
.
OuterClass
can be accessed in OuterClass
and its subclasses. The
OuterClass
can be accessed from any class in the same package.
OuterClass
can be accessed from anywhere. InnerClass
Can access public, protected, and default members in OuterClass
, but not private members. The above is the detailed content of Things to note when using access modifiers for Java functions. For more information, please follow other related articles on the PHP Chinese website!