Wednesday, August 11, 2010

About innerclasses ?

There are several types of inner classes.

Inner classes
method-inner classes
Anonymus inner classes
static nexted inner classes


The usage of each inner class has shown below :


Inner class:


class Outer
{
class Inner
{
public void innerClassMethod()
{
System.out.println("You are in the method of inner class");
}
}
public void outerClassMethod()
{
Inner i=new Inner();
i.innerClassMethod();
}
}

The above represents the how to create a inner classes and how to use them. As you know when we compile a java file there will be a class files will be generated for all the classes defined in the java file. For inner classes also it will generate the class file as Outer$Inner.class.(But we can not run using Outer$Inner directly).

We can also use the innerClassMethod() in the main also (not only in outerClassMethod()) by creating the object of inner class in the main as below

Outer.Inner innerInstance= new Outer.new Inner()
innerInstance.innerClassMethod();

method-inner classes:
class Outer
{

public void outerClassMethod()
{
class Inner
{
public void innerClassMethod()
{
System.out.println("You are in the method of inner class");
}
}
Inner i=new Inner();
i.innerClassMethod();
}
}

Creating object for method inner classes:

We can only create the object of method-inner classes only in the methods in which the inner class is defined like above.

Anonymous Inner Classes :
class A{
public void sampleMethod() {
System.out.println("Sample Method");
}
}
class B{
A p = new A() {
public void sampleMethod() {
System.out.println("anonymous Sample Method");
}
};
}


If you observe class B, there is class defined with the name outer method A. We can consider that method subclass of class A. But without name. Thats why it is called as Anonymous inner classes.

Static inner classes:
class BigOuter {
static class Nest {void go() { System.out.println("hi"); } }
}
class Broom {
static class B2 {void goB2() { System.out.println("hi 2"); } }
public static void main(String[] args) {
BigOuter.Nest n = new BigOuter.Nest(); // both class names
n.go();
B2 b2 = new B2(); // access the enclosed class
b2.goB2();
}
}

Above i have defined two types of using static inner classes.

2 comments:

  1. As my understanding, Inner classes place a major role in Swing programming.


    Cheers

    ReplyDelete
  2. Nice post . . Very Useful information

    Dhung.com provide interview question and answer for all company.

    ReplyDelete