Previous | Home | Next |
There is a very little difference between the static inner classes and non-static inner classes, but in terms of their functionalities both are very different.
In java each instance of the inner class is implicitly associated with an instance of its enclosing class which allows the inner class to directly access the non-static member variables and functions of its enclosing class.
A non-static inner class maintains a reference to its enclosing class, an instance of a non-static inner class can not be created unless there is an instance of the enclosing class. Instances of the inner class maintain a reference to their enclosing instance which is assigned automatically upon object creation.
If your member class doesn't require access to the enclosing instance make it static to save resources. Because a non-static inner class cannot exist without an enclosing class's instance it is very rare to see non-static inner classes that aren't private or package protected. Static member classes are frequently declared public. The syntax and usage of non-static inner classes can be shown via the following code snippet,
Example
Java Tutorialsclass NonStaticInnerExample { public static void main(String args[]) { new Addition().sum(); // creating the object of Addition class and calling sum method on it. new Addition().new Addition1().sum(); // creating the object of Addition1 class using the object of Addition class int d=new Addition().a; // storing value of a in d int e=new exem().new Addition1().c; // storing value of c in e System.out.println("the value of a in outer class is:"+d); //printing values of d and e System.out.println("the value of c in inner class is:"+e); } } Java Tutorialslass Addition // enclosing or top level class { int a=10; int b=20; void sum() { System.out.println("the sum of two numbers in enclosing class is:"+(a+b)); } Java Tutorialslass Addition1 // Non-Static member class { int Java Tutorials=70; void sum() { System.out.println("The sum of three numbers in inner class is :"+(a+b+c)); } }
Previous | Home | Next |