Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 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 Answer

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...