What are Inner Classes and its types (Regular, Method local,Anonymous ) In Java

Inner classes are one of the most fundamental topics of java . So in this post first we will discuss what are inner classes and what are the different type of inner classes.  Inner classes is an important topic if you are about to give OCJP exam. Although in real world coding , inner classes are not used frequently. But It is better to have an idea , what classes are inner and how to write it in java.


Read Also :  Difference between == and equals method


What is Inner Class ?

Inner class is the class with in a class . It is treated like a member of the outer class and  has access to all the members of the outer class even those which are declared as private .

For example :


class Outer
{
    private name ;
    class Inner {   }         // Inner class can access the name member
                             // of the Outer class  even though it is
                            // declared as private
}


How to compile the above code  :

Simple , just write the name of the outer class and following with .java extension

So , we can compile the above code as

javac   Outer.java

On executing the above line , you will notice that , it produces the twins (that is two classes , in one command )   , namely ,

    Outer.class (expected)
    Outer$Inner.class  (byproduct)

Now , come the turn to execute the byte code

You can not write

java Outer$Inner.java  , As the regular inner class can not have static  declarations of any kind .  The only way you can access the inner class is through the live instance of the Outer Class .
or in other words
One can interact with Inner class at runtime only , after creating the Outer class instance .


RULE OF THUMB :


To create the instance of  the inner class you need to have the instance of the outer class .

Now if you want to access the inner class outside the Outer class , then you need to write down the following code :

public static void main (Strings args[])
{
     Outer            outerclassobject = new Outer();
     Outer.Inner    innerclassobject = outerclassobject.new  Inner();
}

if you want to write the above code in one line then
 
      Outer.Inner  innerclassobject = new Outer().new Inner();        
         
Instantiating an inner class is the only scenario in which you'll invoke new on an instance as opposed to invoking new to construct an instance.

Following modifiers can be applied to a regular inner class

public ,protected ,private ,final , static and strictfp


Method Local Inner Class 

There is also another type of inner class called as Method-Local inner class .The regular inner class can be scoped inside one class but outside the method . But the method local inner class  is defined inside the method body itself.

Below is the example showing instantiation of the method local inner class .


class  Outer2 {
    private String x = "Outer2";
    void doStuff() {
        class Inner {
            public void seeOuter() {
                System.out.println("Outer x is " + x);
            } // close inner class method
        } // close inner class definition
        
        Inner one = new MyInner(); // This line must come after the class
        one.seeOuter();
    } // close outer class method doStuff()
} // close outer class

For the inner class to be used, you must instantiate it, and that instantiation must happen within the same method, but after the class definition code. A method-local inner class cannot use variables declared within the method (including parameters) unless those variables are marked final .




Anonymous Inner Classes

As the name suggests ,  word anonymous means not identified with name. So,
There is no name of the anonymous inner classes , and their type must be either a subclass of the named type or an implementer of the named interface.


Please find the example of Anonymous class below  :


class Apple {
    public void iphone() {
        System.out.println("iphone");
    }
}
class Mobile {
    Apple apple = new Apple() {
        public void iphone() {
            System.out.println("anonymous iphone");
        }
    };


Note  :
An anonymous inner class is always treated like a statement in the class code , and remember to close the statement after the class definition with a curly brace. It is rare to found the curly braced followed by semi colon in java .
See the last line of the above code

Read Also : File Handling Java Code with Example


Points to remember about Anonymous Inner Class :

1. Due to polymorphism, the only methods you can call on an anonymous inner class reference are those defined in the reference variable class (or interface), even though the anonymous class is really a subclass or implementer of the reference variable type.

2. An anonymous inner class can extend one subclass or implement one  interface. Unlike non-anonymous classes (inner or otherwise), an anonymous inner class cannot do both. In other words, it cannot both extend a class and implement an interface, nor can it implement more than one interface.

3. An argument-defined inner class is declared, defined, and automatically instantiated as part of a method invocation. The key to remember is that the class is being defined within a method argument, so the syntax will end the class definition with a curly brace, followed by a closing parenthesis to end the method call, followed by a semicolon to end the statement: });


Please mention in the comments in case if you have any doubts related to inner class and its type.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry