r/javahelp • • Sep 12 '19

What is the difference between "[ClassName].this.variable" and simply, "this.variable"

So I came across this class called:

AutoCompleteComboBoxListener()

with a node called comboBox.

And inside its methods, such as

selectClosestResultBasedOnTextFieldValue(),

they refer to the comboBox of AutoCompleteComboBoxListener() as

AutoCompleteComboBoxListener.this.comboBox.getItems();

Is it different from:

this.comboBox.getItems();

Thanks a lot everyone.

17 Upvotes

9 comments sorted by

View all comments

Show parent comments

1

u/dg_713 Sep 16 '19

Thanks for the additional info. Can you explain further what you mean exactly when you said this?

1

u/8igg7e5 Sep 16 '19

Consider the following

class Outer {
    private int[] pool = ... ; // Let's say this is 10 million entries
    private Random rand = new Random();

    public Inner makeRandomValue() {
         return new Inner();
    }

    public class Inner {
        private int value;

        private Inner() {
            int i = Outer.this.rand.nextInt(Outer.this.pool.length);
            this.value = Outer.this.pool[i];
        }

        public int getValue() { return value; }
    }
}

If you do...

Outer outer = new Outer();
Inner inner = outer.makeRandomValue();

Then the outer instance will not be garbage collected until the inner instance is garbage collected.

Rearranged as follows, this is no longer a problem...

class Outer {
    private int[] pool = ... ; // Let's say this is 10 million entries
    private Random rand = new Random();

    public Inner makeRandomValue() {
         int i = rand.nextInt(pool.length);
         return new Inner(pool[i]);
    }

    public static class Inner {
        private int value;

        private Inner(int value) {
            this.value = value;
        }

          public int getValue() { return value; }
    }
}

Or something like that.

1

u/dg_713 Sep 16 '19

Ok, I get it now, it's because inner instance is still referencing the values stored in the outer instance, is that it?

1

u/8igg7e5 Sep 16 '19

No it's referencing the outer instance. An instance of a non-static inner class keeps a link to the instance of the outer class that was used to create it.