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.
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.)
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?
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With