Inner Classes and Static Inner Classes

 

Inner Classes

If you are having one class in another class then first class is called Inner class and second class is called Outer Class.

 

class ClassA

{

        private void Method()

        {

            //this is the method for ClassA

        }

 

        class ClassB

        {

            private void Method()

            {

                //this is the method for ClassB

            }

        }

}

 

As shown above, ClassA called Outer class and ClassB called Inner class. Inner classes have a lot of importance because you can group the classes that are logically belong together and to control the visibility of one within other.

You can access the Inner classes by creating the object for Outer class.

 

Static Inner Classes

If you don’t want a connection between the inner class object and the outer class object, then you can make the inner class static. To understand the meaning of static when applied to inner classes, you must remember that the object of an ordinary inner class implicitly keeps a reference to the object of the enclosing class that created it. This is not true, however, when you say an inner class is static.

 

class ClassA

{

        private void Method()

        {

            //this is the method for ClassA

        }

 

        static class ClassB

        {

            private static void Method()

            {

                //this is the method for ClassB

            }

        }

}

 

As shown above ClassB is called as static inner class.

 

A static inner class means:

1. You don’t need an outer-class object in order to create an object of a static inner class.

2. You can’t access an outer-class object from an object of a static inner class.

 

static inner classes are different than non-static inner classes in another way, as well. Fields and methods in non-static inner classes can only be at the outer level of a class, so non-static inner classes cannot have static data, static fields, or static inner classes. However, static inner classes can have all of these