Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

syntax

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.

like image 428
amara Avatar asked May 08 '10 06:05

amara


3 Answers

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

like image 97
JesperE Avatar answered Nov 15 '22 20:11

JesperE


I think it's just a simple way of clarifying which this one means (since this, without the qualifier, refers to the inner this which is a reference to an object of type B).

Since this is a reserved keyword it can't be confused with some static filed/method of class A.

I supposed they could have introduced some other keyword like enclosing and let you go through enclosing.this (similar to the super keyword). I just don't think they saw it as necessary to introduce a new keyword in this situation.

Would you prefer some other syntax?

like image 27
aioobe Avatar answered Nov 15 '22 22:11

aioobe


Why is it done that way? Really, it's just because of the way it is. It works, it sort of makes sense, and there's no need to come up with fancy syntax to do the job.

When you see something like this:

x.y.z

The . can mean a lot of things:

  • Subpackage separator
  • Member field access
  • Nested type separator

In other words, the . is overloaded to serve many grammatical functions within Java programming language. It may lead to confusion, and it can be problematic, but that's just the way it is.

It helps to follow naming convention, but certain things can still look ambiguous and/or confusing.

See also

  • Sun Naming Conventions
  • JLS 6.5 Determining the Meaning of a Name
    • This section has many examples showing how names can be resolved
like image 2
polygenelubricants Avatar answered Nov 15 '22 21:11

polygenelubricants