Tuesday, July 10, 2012

What is "this" in Java?


So in learning Java I found the "this" keyword to be a bit of an odd item to work with. It is pretty obvious now but initially it was confusing and some google-fu helped clear things up. The one thing that was a bit subtle was the construct:

InnerClass innerClassObject = this.new innerClassConstructor();

So here is the answer. When you have an Inner Class, it can't be handled directly at all and needs to be referenced via an instanced object of its encapsulating Outer Class. In other words, you need an object created for the Outer Class before you can create an object of the Inner Class. The code would normally look as follows:

OuterClass.InnerClass innerClassObject = new outerClassConstructor().new innerClassConstructor();


This is how you would refer to and create an Inner Class object from anywhere (say in the "main" method).
However, the code changes if you are doing the same from within the scope of the Outer Class itself. In that case it will look like the first line. This is because the "this" is being used to call the constructor of the Outer Class to create an object (much like "new outerClassConstructor()" call) which returns a reference (address) to the Outer Class object. After that the "new" for the Inner Class can be called using the Outer Class reference.
The left-hand side no longer refers using OuterClass.InnerClass as within the scope of the "OuterClass" it is clear what is "InnerClass".  The example looks like:

class OuterClass {
    anOuterClassMethod(){
        InnerClass innerClassObject = this.new innerClassConstructor();
            ...
    }
    class InnerClass{
        innerClassConstructor(){
            ...
        } 
    }
}

Here is a reference to another page that describes things similarly:

Here is the tutorial that I came across this construct initially:

No comments:

Post a Comment