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?
Yes, they are the same.
something.new InnerClass(...)
is the most general syntax for creating an instance of an inner class, wheresomething
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 meansthis.new InnerClass(...)
, just like how when you write instance variables or method calls without explicitly accessing it through a dot, it impliesthis.
(someInstanceVariable
implicitly meansthis.someInstanceVariable
).