I was writing this code:
public class GuiSelectionList<T> extends GuiList<SelectableItem> {
...
public void add(T element) {
list.add(this.new SelectableItem(element));
}
public class SelectableItem {
public T data;
public boolean selected;
public SelectableItem(T data) {
this.data = data;
}
}
}
And I saw that my IDE does not complain whether I use:
list.add(this.new SelectableItem(element));
or
list.add(new SelectableItem(element));
My question is: Are both the same thing?
Creating an inner class is quite simple. You just need to write a class within a class. Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class.
An inner class has access to all fields and methods (including private fields and methods) of its outer containing class. Inner classes cannot implement interfaces. An inner class object contains implicit reference to the enclosing class object.
Yes, they are the same.
something.new InnerClass(...)
is the most general syntax for creating an instance of an inner class, where something
is an expression that evaluates to a reference to an instance of the outer class (remember that every inner class instance has a reference to an outer class instance).
When the something.
is omitted, i.e. new InnerClass(...)
, and you happen to be in an instance method of the outer class, then it implicitly means this.new InnerClass(...)
, just like how when you write instance variables or method calls without explicitly accessing it through a dot, it implies this.
(someInstanceVariable
implicitly means this.someInstanceVariable
).
They are essentially the same since SelectableItem
is an inner, non static class to GuiSelectionList
and you're instantiating it from the GuiSelectionList
class.
See this related SO question about "object.new".
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