Sunday, October 11, 2009

Static Inner Class Example in Java

Hello and welcome back to Java Code Online, there has been a request from many of my users to come up with an example for static inner class. So the topic of today is to to illustrate Static Inner Class in action.

You may any time check my previous article on Static Inner Class in Java for an illustration of what it is and what are the details for the other type of Inner classes in Java. today I will straight move to the example for it.

------------------------------------
class Cover
{
         static class InnerCover
             {
              void go()
                  {
                       System.out.println("I am the first Static Inner Class");
                  }
            }
 }

class Broom
{
         static class InnerBroom
        {
                  void go1()
                   {
                         System.out.println("I am second Static Inner Class");
                    }
         }

         public static void main(String[] args) {
         // You have to use the names of both the classes
         Cover.InnerCover demo = new Cover.InnerCover();
         demo.go();
        // Here we are accessing the enclosed class
        InnerBroom innerBroom = new InnerBroom ();
        innerBroom .go1();
 }
}
------------------------------------

When the above code is executed, the output is something like as displayed below:-
------------------------------------
 I am the first Static Inner Class
 I am second Static Inner Class
------------------------------------

We know that a Static inner class is just a class which is a static  member of the main class. So the same concept is applied here. Here we have two outer classes, one is called Cover, and the second is called Broom. Both of these outer classes have one static class within them.

The method of accessing both the inner classes is shown in the main method of the Broom class. I hope the example will be helpful to all of you. Do post a comment if you have any query or if you liked the article. Java Code Online will soon be back with yet another informative article.