Home »

Beauty of Inner Classes

Java allows you to create a class within another class and this is called inner class.

Why to create a nested class? 

  • Logical way of grouping and putting them together. Example say we create class Phone within a class Student to logically group them together.
  • Increases encapsulation; Class Student can access private members of class Phone as being inner class of which, otherwise member variables had to be declared as public to give access to class Student.

These are of several types of inner classes:

1: Static Nested class;  An inner class declared as static can access only static members of parent class .

  public class Student {
	static int roll;
	static String name;

	static class Phone{
		int phone_no;
	}
        }

Static inner class can be access rom out side in following way

InnerClass.StaticInner staticObj= new InnerClass. StaticInner ();

2: Inner Class; A normal non static nested class which is associated with the instance if the holding class.

class OuterClass {
    ...
    class InnerClass {
        ...
    }
}

This is how we create instance if inner class:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

3: Local inner class: Local inner class are those inner classes which are defined within the a specific block. Usually they are defined inside a method , also known as method local inner class. These are highly encapsulated not accessible out side the block , can access members of enclosing class and final local variables.

   public void processData(Data data){
     class DataWorker implements Runnable{
       DataWorker(int data){
       }
       public void run(){
       **
       }
    }

   Thread runner = new Thread(new DataWorker(data));
   runner.start();
  }

4: Anonymous inner class: This my favourite and most popular way of using inner class. Here we do not declare a class in advance and then create its object, as we do in traditional way. Rather you can say we construct a class on the fly at the time when its object is required. This is suitable for some composite objects where we need only one object and there we club class declaration and initialisation together.

public void processData(Data data){
    Runnable runable = new Runnable() {
	@Override
	public void run() {
		// TODO Auto-generated method stub
	}
    };

   Thread runner = new Thread(runable);
   runner.start();
  }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: