Home > Java > javaTutorial > How does a Java anonymous inner class access member variables of an outer class?

How does a Java anonymous inner class access member variables of an outer class?

WBOY
Release: 2024-05-01 09:27:02
Original
1190 people have browsed it

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.

Java 匿名内部类是如何访问外部类的成员变量的?

Java's mechanism for anonymous inner classes to access external class member 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 secretOuterClass 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();
    }
}
Copy after login

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 anonymous inner class can only access the member variables of the outer class, but not its methods.
  • If the member variable of the outer class is final, the anonymous inner class can only read but not modify the variable.

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template