Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of this.new and bare this in inner classes

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?

like image 404
aziis98 Avatar asked Jun 17 '15 14:06

aziis98


People also ask

How do you create an inner class?

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.

Which statement with respect to inner class is true?

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.


2 Answers

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

like image 115
newacct Avatar answered Sep 25 '22 15:09

newacct


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

like image 28
Buhake Sindi Avatar answered Sep 22 '22 15:09

Buhake Sindi