Thursday, May 2, 2013

Java / Inner classes


Inner classes.
There are two types of inner classes:
- static (static nested classes)
- non-static (inner classes)

Non-static nested classes have access to other members of the enclosing class,
even if they are declared private.
Static nested classes don't have access to other members of the enclosing class.

There are few reasons for using nested classes.
- logical grouping classes used in one place
- increasing encapsulation
- more readable and maintainable code

public class MyNested 
{
 private int x = 10;
 private int y = 15;
 
 public void showAddition()
 {
  Operation o = new Operation();  
  System.out.println( o.add() );
 }
 
 class Operation
 {
  private int add()
  {
   System.out.println( "Adding" );
   return x+y;
  }
 }
 
 // ! 
 // Static nested classes don't have access to members of enclosing classes 
 static class StaticOperation
 {
  private int add()
  {
   return x+y;
  }
 }
 
 public static void main(String[] args) 
 {
  MyNested n = new MyNested();
  n.showAddition();
  
  // To instantiate an inner class, you must first instantiate the outer class. 
  // Then, create the inner object within the outer object 
  MyNested.Operation op = n.new Operation();
  op.add();

 }
}

No comments: