Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 views
in Technique[技术] by (71.8m points)

java - Access outer class from inner class: Why is it done this way?

So most of us know how to access an outer class from an inner class. Searches with those words give oodles of answered questions on that topic. But what I want to know is why the syntax is the way it is.

Example:

public class A
{
    private class B
    {
        public void c()
            {A.this.d();}

        public void d()
            {System.out.println("You called the d() in the B class! Oh noes!");}
    }

    public void d()
        {System.out.println("You've called d()! Go, you!");}
}

Why is it A.this.d()? It looks like this is a static field of class A, but... * am confused *

Forgive me if this is a repeat; like I said, searches with those words give how-answers.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A non-static inner class is always associated with a specific instance of the outer class. The A.this syntax is just a way to refer to this instance. I cannot think of any other simpler or clearer way of doing this. My first reaction when I saw this syntax was "ouch, ugly", but when I though a little about it I realized that it was pretty neat.

(Yes, it does look like accessing a static field, but then again, you cannot have a static field this, so it isn't ambiguous.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...