Inner classes in Java, the mystery within.

java-inner-classesInner classes, also called Nested Classes, are nothing but classes that are defined within other classes. The nesting is a relationship between classes, not objects.

Inner classes have clearly two benefits, name control & access control. In Java, this benefit is not as important because Java packages give the name control.

Java inner classes have feature that makes them richer and more useful. An object of an inner class has an implicit reference to the outer class object that instantiated it. Through this pointer, it gains access to any variable of the outer object. Only static inner classes don’t have this pointer. It is actually invisible when we write the code, but compiler takes care of it. Inner classes are actually a phenomenon of the compiler and not the JVM.

Inner classes may be defined with following access modifiers : public, protected, private, or with default package access.

The syntax for inner class is as follows:

[modifiers] class OuterClassName {
    code...
    [modifiers] class InnerClassName {
        code....
    }
}

Inner Classes:

Following properties can be noted about Inner classes:

  • The outer class (the class containing the inner class) can instantiate as many number of inner class objects as it wishes, inside it’s code.
  • If the inner class is public & the containing class as well, then code in some other unrelated class can as well create an instance of the inner class.
  • In above case the inner class can be created as follows:
	<OuterClassName> outerObj = new <OuterClassName>(arguments);
	outerObj.<InnerClassName> innerObj = outerObj.new <InnerClassName>(arguments);
  • No inner class objects are automatically instantiated with an outer class object.
  • If the inner class is static, then static inner class can be instantiated without an outer class instance, otherwise, the inner class object must be associated with an instance of the outer class.
  • Inner class code has free access to all elements of the outer class object that contains it, by name (no matter what the access level of the elements is), if the inner class has a varible with same name then the outer class’s variable can be accesse like this:
	<OuterClassName>.this.<variableName>
  • The outer class can call even the private methods of the inner class.

Static Inner Classes:

Syntax for static inner class is as follows:

<access-specifier> class OuterClassName {
    public static class <StaticInnerClassName> {
        . . .
    }
    . . .
}

for static inner classes following additional properties hold:

  • Static members of the outer class are visible to the static inner class, what ever their access level be.
  • Non-static members of the outer class are not available, because there is not instance of the outer class.
  • An inner class may not have static members unless the inner class is itself marked as static.
  • Sometimes static nested class are not refered to as inner class at all, as they don’t require outer classes instance.
  • A static inner class is just like any other inner class, but it dose not have the reference to its outer class object that generated it.

There are two more types of inner classes, i.e local inner classes & anonymous inner classes. The local inner class are defined within a method. Anonymous inner classes are also defined with in a method but have no name.

Local Inner Classes:

Syntax of the local inner class is as follows:

<access-specifier> class <OuterClassName> {
	code...
	<access-specifier> <return-type> <MethodName>(<arguments>){
		class <LocalInnerClassName>{
			code...
		}
		code...
	}
	code...
}
  • Local classes are never declared with an access specifier (that is, public or private). Their scope is always restricted to the block in which they are declared.
  • Local classes have a great advantage: they are completely hidden from the outside world.
  • They can not only access the instance variables but local variables of the method (in which they are defined) as well, but the local varible has to be declared final.

Anonymous Inner Classes

When using local inner classes, you can often go a step further. If you want to make only a single object of this class, you don’t even need to give the class a name.

Such a class is called an anonymous inner class. Usually the inner class extend some interface or extend other class.

This syntax for anonymous classes is very cryptic.

new SuperType(construction parameters) {
	inner class methods and data
}
  • Here, SuperType can be an interface, such as ActionListener; then, the inner class implements that interface. Or SuperType can be a class; then, the inner class extends that class.
  • An anonymous inner class cannot have constructors because the name of a constructor must be the same as the name of a class, and the class has no name. Instead, the construction parameters are given to the superclass constructor. In particular, whenever an inner class implements an interface, it cannot have any construction parameters. Nevertheless, you must supply a set of parentheses as in
	new InterfaceType () { methods and data }
  • It is recommended to refrain from using them as many programmers find too many anonymous classes hard to read.

The following table shows the types of nested classes:

Types of Nested Classes
TypeScopeInner
static nested classmemberno
inner [non-static] classmemberyes
local classlocalyes
anonymous classonly the point where it is definedyes
An inner class may not have static members unless the inner class is itself marked asstatic

Class Files Generation for Inner Classes

As we mentioned earlier each class can have more than one inner classes. Once the main class is compiled which has several inner classes, the compiler generates separate class files for each of the inner class. Have a look at below example.

// Main class
public class Main {

	// Inner class Test1
	class Test1 {
	}

	// Inner class Test2
	class Test2 {
	}


	public static void main(String [] args) {
	
		// Anonymous inner class 1
		new Object() {
		};

		// Anonymous inner class 2
		new Object() {
		};

		System.out.println("Hello World");
	}
}

Here we have a Main class which has four inner classes. Test1, Test2, Anonymous inner class 1 and Anonymous inner class 2. Once we compile this class using javac command, the compiler will generates following class files.

Main.class
Main$Test1.class
Main$Test2.class
Main$1.class
Main$2.class


22 Comments

  • google.com/accounts/o8… 5 December, 2009, 16:56

    thank you for this article,but here’s code is not right.
    ****************************************************************************
    outerObj = new (arguments);
    outerObj. innerObj = outerObj.new (arguments);
    ********************************
    as you say “The nesting is a relationship between classes, not objects.”
    so, right code should like this:

    outerObj = new (arguments);
    . innerObj = outerObj.new (arguments);

    at last, thank you again.

    • aditya 14 July, 2012, 15:14

      to instantiate static inner class in another class
      the synatx is
      . objectname=new .();

      to instantiate non-static inner class in another class
      the synatx is
      outerobjname=new ();
      . innerobjectname=outerobjname.new ();

      to refer both at a time im posting it.

  • google.com/accounts/o8… 5 December, 2009, 17:05

    oh,my sorry.
    the code:

    <OuterClassName> outerObj = new <OuterClassName>(arguments);
    outerObj.<InnerClassName> innerObj = outerObj.new <InnerClassName>(arguments);

    new code:

    <OuterClassName> outerObj = new <OuterClassName>(arguments);
    <OuterClassName>.InnerClassName> innerObj = outerObj.new <InnerClassName>(arguments);

  • hotshot309 13 February, 2010, 23:08

    This is really helpful and clear, other than the mistake pointed out by the last poster. Can you fix the code in the article as you mentioned above?

  • Manoj Kumar Singh 9 July, 2010, 15:57

    Great Article..

    Post more related article.

    Thanks,
    Manoj SIngh

  • Madhu 3 June, 2011, 3:07

    It would have been much better if you had given some examples for the syntax you provided. Just seeing the syntax, its hard to visualize, examples would make it much easier.

    Thanks.

  • arti nama 26 November, 2011, 15:29

    It’s actually a great and helpful piece of info. I’m satisfied that you shared this useful info with us. Please keep us informed like this. Thanks for sharing.

  • Prasanth 10 December, 2011, 14:49

    can we have more than one inner class inside the outer class. if so will a class file be created for each inner class,??

    • Viral Patel 10 December, 2011, 16:23

      Hi Prasanth,
      I have added a section Class Files Generation for Inner Classes in above tutorial. Hope that answers your query.

  • Bibek 18 December, 2011, 21:50

    Hi,
    Good work ! well explained. but if you can post uses in our inner classes it would be better.

    Thanks!

  • kumara swamy 8 March, 2012, 11:56

    hi

    it is good explain and I have get more about innner class constructor topic .Please send to E-mail
    we can access inner class by using new . inside the outer class method

  • Vishva Patel 9 May, 2012, 14:43

    Very helpful, Thanxxxxx.

  • harsh sondhi 21 July, 2012, 23:37

    Article i was looking for years…made inner class concepts very clear..

  • zubair 3 September, 2012, 12:46

    Good article. Keep these comming.
    Regards,
    Zubair

  • Sushanth Sivadas 20 September, 2012, 22:54

    Hiiii………
    this has got great stuffs that helps newbies like me…… v r always looking forward for things like this………
    i wish if i can get a vivid idea about the terms “name control”&”access control” which is mentioned in the intro paragraphs….

    thank u so much……..

  • Bharat Verma 24 September, 2012, 11:05

    Can a object of outer class in main function … directly calls the private or public methods of inner class or not ?

    OuterClass inc = new OuterClass();

    inc.InnerClassMethod();

    is it wrong if yes then why ?

  • Solai 18 October, 2012, 23:46

    can any one pls tell me the benefits of these inner class!!!?
    i am clear about this concept!! but little bit confused!
    please say where we will use this inner class!

  • sajindhas 22 November, 2012, 15:49

    I need more explain the inner class with proper explanation. Any one plz help me…

  • Prasanna Mallick 14 December, 2012, 1:08

    Inner classes are introduced to handle AWT events & also to increase encapsulation.

  • satish 17 December, 2013, 12:26

    Here is one example on anonymous inner class:

    interface MyInterface{
            public void test();
    }
    class Bahar{
            public void fun(){
                    new MyInterface() {
                            @Override
                            public void test() {
                                    System.out.println("got it");
                            }
                    }.test();
            }
    }
    public class NestedDemo2 {
            public static void main(String[] args) {
                    Bahar b = new Bahar();
                    b.fun();
            }
    }
    
  • evmika 3 February, 2014, 7:12

    >>Inner classes, also called Nested Classes

    It’s not correct.
    According to JLS, nested class != inner class. inner class is a special kind of nested class.
    JLS has a very precise terminology, it’s better to follow it.

    “static inner class” is totally meaningless also.

  • Nishant ranjan 29 May, 2014, 23:12

    Very very useful.. thanxx ..

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current ye@r *