Observations

The inner class in main is instantiated using outer.new operator. This way we associate a inner class with outer class instance.

Inside outer class constructor we used this.new operator. This is a way we instantiate the inner class from within the outer class object.

Use of Outer.this.x – The variable x is common to both inner and outer class. To access the outer x within the inner class you have to use OuterClassName.this.x operator. This syntax is used only within inner class.

Local Inner Class

Local Inner Class are declared within a member method of class. They are instantiated when the method is called and it goes out of scope when method returns. The Local Inner class can be instantiated only within the method. Properties of local inner class are

They do not have access specifier.

They cannot be declared static or have static members.

They cannot access any local variable of the defined in the method unless they are final.

You can see the declaration of two local inner class within calculateProperty() method. Notice how they can access the radius and property members of LocalOuter class.

We mentioned in properties of Local Inner Class that they can’t access the local variables of calling method. Why?

We know that JVM does not understand the concept of inner class. Inner Classes are compile time constructs. Whenever compiler encounters a inner class it creates bytecode of a top level class. So in essence it creates two top level class i.e. Outer Class and inner class. Now there is no way by which a object can be aware of local variables of a method of another class. However if the variable is declared final then a copy of it is stored in outer class from where the inner class can get its handle.

Anonymous Class

Anonymous Class is a Local Inner Class that has no name. Anonymous Inner Class is declared and instantiated in one single statement. Anonymous class class has to extend a class or implement interfaces. Like any other inner classes when a class containing anonymous class is compiled then two top level class is created.

Share this:

About Niraj Singh

I am CEO and CoFounder of a startup "Aranin Software Private Limited, Bangalore. I completed my graduation in 2002 as an Aerospace Engineer from IIT Kharagpur.
I love working on new ideas and projects and recently released my first open source project JaiomServer "http://jaiomserver.org".
I have 9 years of experience in IT industries most of which I have spent in developing community applications for various clients using java. Some of the sites in which I have actively involved with are
hgtv.com, food.com, foodnetwork.com, pickle.com, diynetwork.com etc.