Ali Ali - 6 months ago 7
Java Question

Difference between instantiating with "this.new InnerClass()" and "new InnerClass()"

I was reviewing some material for java 8 certification and came across code similar to the one shown below. Could someone explain what the difference is between using 'this' keyword to instantiate the inner class and without using the 'this' keyword? Both way of instantiating InnerClass seem to work (no compiler error or runtime error).

Is this similar to using the class name to access public static members instead of instance name? Both ways work but using class name is desired over using instance name.

public class OuterClass {

class InnerClass { } // Define Inner class

private InnerClass innerclass; // private member
private InnerClass thisInnerClass; // private member

public OuterClass() {
this.innerclass = new InnerClass(); // without 'this' keyword
this.thisInnerClass = this.new InnerClass(); // with 'this' keyword
}
}


=====================================

Edit:
There is no difference between the two.
I compiled both of the following versions and the md5 sum is the same for both versions. Using the 'this' reference and not using the 'this' reference produces the same bytecode.

public class OuterClass {

class InnerClass { } // Define Inner class

private InnerClass innerClass; // private member

public OuterClass() {
this.innerClass = new InnerClass(); // without 'this' keyword
}
}


MD5 Sum for compiled above code (without 'this' reference):

MD5 (OuterClass$InnerClass.class) = 7f1679f1c7a0201164ce5eb03fe29699

MD5 (OuterClass.class) = bf7419b01f8f7c24d2892d10c4fd6e05

public class OuterClass {

class InnerClass { } // Define Inner class

private InnerClass innerClass; // private member

public OuterClass() {
this.innerClass = this.new InnerClass();// with 'this' keyword
}
}


MD5 Sum for compiled above code (with 'this' reference):

MD5 (OuterClass$InnerClass.class) = 7f1679f1c7a0201164ce5eb03fe29699

MD5 (OuterClass.class) = bf7419b01f8f7c24d2892d10c4fd6e05

Answer

My understanding is that there is no difference between the two. It is like calling foo() or this.foo() from within the class foo() is contained in. this is implied when it is not written explicitly.

Comments