Wednesday, February 8, 2017

Difference between Inner Class and Nested Class

Let's look at the differences between the two types of Inner Classes.

Before jumping into the theoretical part, let's have a look at a code example:

public class OuterClass {
      private String someVariable = "Non Static";

     private static String anotherStaticVariable = "Static";  

     OuterClass(){

     }

     //Nested classes are static
     static class StaticNestedClass{
        private static String privateStaticNestedClassVariable = "Private Static Nested Class Variable"; 

        //can access private variables declared in the outer class
        public static void getPrivateVariableofOuterClass(){
            System.out.println(anotherStaticVariable);
        }
     }

     //non static
     class InnerClass{

         //can access private variables of outer class
         public String getPrivateNonStaticVariableOfOuterClass(){
             return someVariable;
         }
     }

     public static void accessStaticClass(){
         //can access any variable declared inside the Static Nested Class 
         //even if it private
         String var = OuterClass.StaticNestedClass.privateStaticNestedClassVariable; 
         System.out.println(var);
     }

}

Properties of a Nested Class:

1. They are static
2. Can be private
3. Private variables declared in the Outerclass is accessible in the inner class
4. private variables declared inside the Nested classes are accessible in the outer class. Look at the accessStaticClass.

 Properties of a InnerClass:

1. They are associated with the instance of the outer class.
2.  All variables declared inside an inner class can accessed from outside.

Now let's have a look at the test cases:

public class OuterClassTest {
    public static void main(String[] args) {

        //access the Static Nested Class
        OuterClass.StaticNestedClass.getPrivateVariableofOuterClass();

        //test the private variable declared inside the static nested class
        OuterClass.accessStaticClass();
        /*
         * Inner Class Test
         * */

        //Declaration

        //first instantiate the outer class
        OuterClass outerClass = new OuterClass();

        //then instantiate the inner class
        OuterClass.InnerClass innerClassExample =  outerClass. new InnerClass();

        //test the non static private variable
        System.out.println(innerClassExample.getPrivateNonStaticVariableOfOuterClass()); 

    }

}
This should give you a brief idea about how the static nested class and inner class work. For more information you can read this stackoverflow post.


No comments:

Post a Comment