I didn't imagine that I would encounter radically new syntax in Java anymore at this stage, but lo and behold, I just encountered something:
The exact context and what the code below should do is pretty irrelevant - it's there just to give some kind of context.
I'm trying to synthetically create an event in IT Mill Toolkit, so I wrote this kind of line:
buttonClick(new Button.ClickEvent(button));
But, Eclipse gives me the following error message:
No enclosing instance of type Button is accessible. Must qualify the allocation with an enclosing instance of type Button (e.g. x.new A() where x is an instance of Button).
When I rewrite the line above as follows, it doesn't complain anymore:
buttonClick(button.new ClickEvent(button)); // button instanceof Button
So, my question is: What does the latter syntax mean, exactly, and why doesn't the first snippet work? What is Java complaining about, and what's it doing in the second version?
Background info: Both Button
and Button.ClickEvent
are non-abstract public classes.
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass. InnerClass innerObject = outerObject.
The new operator is used to create the object of member inner class with slightly different syntax. The general form of syntax to create an object of the member inner class is as follows: Syntax: OuterClassReference.
If the inner class is static, then the static inner class can be instantiated without an outer class instance. Otherwise, the inner class object must be associated with an instance of the outer class. The outer class can call even the private methods of the inner class.
For example, to create an object for the static nested class, use this syntax: OuterClass. StaticNestedClass nestedObject = new OuterClass.
Inner classes (like Button.ClickEvent
) need a reference to an instance of the outer class (Button
).
That syntax creates a new instance of Button.ClickEvent
with its outer class reference set to the value of button
.
Here's an example - ignore the lack of encapsulation etc, it's just for the purposes of demonstration:
class Outer { String name; class Inner { void sayHi() { System.out.println("Outer name = " + name); } } } public class Test { public static void main(String[] args) { Outer outer = new Outer(); outer.name = "Fred"; Outer.Inner inner = outer.new Inner(); inner.sayHi(); } }
See section 8.1.3 of the spec for more about inner classes and enclosing instances.
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