Tuesday, July 14, 2015

Java Inner Classes -1 (Member classes)

In Java we can define nested classes . Nested classes only make sense if the class which is nested is only used by outer class. A class which is defined inside another class is known as Inner class.  If you look at JDK code, we could see nested classes present in HashMap code.  This nested class is Map.Entry .  As we all know Entry class only make sense to a Hashmap class .
  Now lets look at different ways of doing it :
  1. Member class :
      A member class acts as a non static member of outer class.  Lets look at an example :

class Outer{ 
      class Inner{

  How do we use this inner class ?  Lets look at that now :
// Working example

 public Class OuterClass {
private int data = 20;
class InnerClass {
 public void printMessage(){
    System.out.println(" Data is :" +data);
public static void main(String args[]){
 OuterClass out = new OuterClass();
 OuterClass.InnerClass in = out.new InnerClass(); // Look for syntax

Some good points :

1. Inner class can access both private and public members of outer class .
2. Inner class cannot be instatiated alone. it is always attached to an outer class instance.
3. Java compiler creates two class files, One  OuterClass.class and second one OuterClass#InnerClass class file for the inner class.

No comments:

Post a Comment