Sunday, 25 September 2016

Java | Static VS Non-Static Nested Classes

Static VS Non-Static Nested Classes

     1.      The instance of static nested class is created without the reference of outer class, which means it does not having enclosing instance
The instance of non-static nested class is created with the reference of object of outer class, in which it has defined , this means it has enclosing instance
    2.      Static nested classes does not need reference of outer class. Non-static nested class requires the outer class reference . you can’t create instance of inner class without creating instance of outer class
   3.      Another difference between static and non-static nested classes is that you can’t access non-static members example: methods and fields into nested static class directly, if you do, you will get error like non-static member can’t be used in static context. While inner class can access both static and non-static no of order classes

If you make a nested class non-static then it also referred as inner class




Class outer
     {
 Private static String message =  ”hello”;
//static nested class
            Private static class MessagePrinter
                        {
//onlystatic member of outer class is directly accessible in nested static class
                        Public void PrintMessage()
                                    {
//compile time error if message field is not static
            System.out.println(“message from nested static class : “ + message);
                                    }
                        }
//non-static nested class also called inner class
            Private class inner
                        {
//both static and non-static member of outer class is accessible in the inner class
                        Public void display()
                                    {
           
System.out.println(“message from non-static nested  class : “ + message);
                                    }
                        }
//create static and non-static nested classes
            Public static void main(String[] args)
                        {
//creating instance of nested static class
            Outer.MessagePrinter printer = new outer. MessagePrinter();
//calling non-static method of nested static class
                        Printer. printMessage();
//creating instance of  non-static nested class
                        Outer.Inner inner = outer.new Inner();
//calling non-static method of inner class
                        Inner.display();
//we can also combine above steps
                        Outer.Inner nonstaticIner = new Outer.new inner();
                        Non-staticIner.display();
                        }
            }

Output :    
                       message from nested static class : hello
                       message from nested static class : hello












No comments:

Post a Comment