The access modifier of a Java function determines the visibility scope of the function, including public, protected, default and private. As a class inside the outer class, the anonymous inner class can access all non-private members of the outer class, so the access rights of its functions are related to the function access rights of the outer class.
The relationship between the access modifiers of Java functions and anonymous inner classes
The access modifiers of Java functions determine the function From which locations it can be accessed. These modifiers include:
Anonymous inner classis a class defined within a class in Java without a specified name. They are typically used to create single-use objects, such as implementing event handlers or comparators.
Anonymous inner classes can access all non-private members of the outer class. Therefore, the access rights of functions in an anonymous inner class are related to the access rights of functions in its outer class. For example:
public class OuterClass { private int privateField = 1; protected int protectedField = 2; int defaultField = 3; public int publicField = 4; public void someMethod() { new Runnable() { @Override public void run() { // 内部类可以访问所有非私有成员变量 System.out.println(protectedField); System.out.println(defaultField); System.out.println(publicField); } }.run(); } }
In the above code, the functions in the anonymous inner class can accessprotectedField
,defaultField
andpublicField
because they are not private.
Practical case:
Suppose we have anEventProcessor
interface, which defines aprocess()
method. We want to create an anonymous inner class to implement theprocess()
method, which can access the data in the outer class.
public class Main { private String data = "Hello"; public static void main(String[] args) { EventProcessor processor = new EventProcessor() { @Override public void process() { // 匿名内部类可以访问外部类中的 data 成员变量 System.out.println(data); } }; processor.process(); } }
In this case, as long as thedata
member variable is not private, functions in the anonymous inner class can access it from the same package or subpackage.
The above is the detailed content of The relationship between Java function access modifiers and anonymous inner classes. For more information, please follow other related articles on the PHP Chinese website!