Behavior of this.new and bare this in inner classes

3.5k views Asked by At

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?

2

There are 2 answers

0
newacct On BEST ANSWER

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

0
Buhake Sindi On

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