Anonymous inner classes access outer class member variables, including private variables, through their this keyword, and access outer class member variables through this just as if the anonymous inner class itself declared these variables.
Anonymous inner classes are inner classes without names, usually used to create one-time class to use. An anonymous inner class can access member variables of its outer class, including private variables.
Access mechanism:
The anonymous inner class accesses the member variables of the outer class through its this
keyword. this
keyword points to an instance of an anonymous inner class, which is actually an instance of its outer class. Therefore, this
can directly access the member variables of the outer class, just as if the anonymous inner class itself had declared these variables.
Practical case:
We create an external class with private member variable secret
OuterClass class
, and create an Anonymous inner class to access this variable:
public class OuterClass类 { private int secret = 42; public static void main(String[] args) { OuterClass类 outer = new OuterClass类(); Runnable r = new Runnable() { @Override public void run() { System.out.println("匿名内部类的 secret:" + this.secret); } }; r.run(); } }
When you run this program, it will output: "Anonymous inner class secret: 42". This is because the anonymous inner class can access the private variables secret
of the outer class OuterClass class
through this
.
It should be noted that:
The above is the detailed content of How does a Java anonymous inner class access member variables of an outer class?. For more information, please follow other related articles on the PHP Chinese website!