Home > DeveloperSection > Forums > Java inner class and static nested class
ezra heywood
ezra heywood

Total Post:145

Posted on    May-12-2015 2:02 AM

 Java Java  Nested  Class 

 1 Reply(s)
 1030  View(s)
Rate this:
What is the main difference between a inner class and a static nested class in Java? Does design /implementation play a role in choosing any of these?

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    May-12-2015 7:09 AM

Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.

Static nested classes are accessed using the enclosing class name:
For example, to create an object for the static nested class, use this syntax:

OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:

class OuterClass {
    class InnerClass {
An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

For completeness note that there is also such a thing as an inner class without an enclosing instance:

class A {
  int t() { return 1; }
  static A a =  new A() { int t() { return 2; } };
Here, new A() { ... } is an inner class defined in a static context and does not have an enclosing instance.

Modified On May-12-2015 07:09:35 AM

Don't want to miss updates? Please click the below button!

Follow MindStick