Home >Java >javaTutorial >The relationship between Java function access modifiers and field access
A Java function's access modifier affects its access to fields in the class: public functions can access all fields, regardless of field access permissions. Protected functions can only access fields with protected or public access. The default function can only access fields with default or public access. Private functions can only access fields with private access.
The access permission modifiers of Java functions can restrict their access to fields in the class access permission. Understanding this connection is critical to maintaining the security and maintainability of your code.
There are four function access permission modifiers in Java:
The access modifier of a function affects its access to fields in the class:
Consider the following class:
public class MyClass { private int privateField; protected int protectedField; int defaultField; public int publicField; public void publicMethod() { // 可以访问所有字段 System.out.println(privateField); System.out.println(protectedField); System.out.println(defaultField); System.out.println(publicField); } protected void protectedMethod() { // 可以访问 protected 和 public 字段 System.out.println(protectedField); System.out.println(publicField); } void defaultMethod() { // 可以访问 default 和 public 字段 System.out.println(defaultField); System.out.println(publicField); } private void privateMethod() { // 只能访问 private 字段 System.out.println(privateField); } }
In this case:
publicMethod()
All fields can be accessed because it is a public method. protectedMethod()
has access to protectedField
and publicField
because it is a protected method. defaultMethod()
has access to defaultField
and publicField
because it is a method visible within the package by default. privateMethod()
can only access privateField
because it is a private method. The above is the detailed content of The relationship between Java function access modifiers and field access. For more information, please follow other related articles on the PHP Chinese website!