Wednesday, November 18, 2015

Java Inner Class

Java inner class or nested class is a class i.e. declared inside the class or interface.
Non-static nested classes are known as inner classes.

Types of Nested classes

There are two types of nested classes non-static and static nested classes.The non-static nested classes are also known as inner classes.
  1. Non-static nested class(inner class)
    • a)Member inner class
    • b)Anonymous inner class
    • c)Local inner class
  2. Static nested class

Member Inner Class :

A non-static class that is created inside a class but outside a method is called member inner class.

/*Java Member inner class --A class created within class and outside method.

If you want to instantiate inner class, you must have to create the instance of outer class.
In such case, instance of inner class is created inside the instance of outer class.

Internal code generated by the compiler:

The java compiler creates a class file named Outer$Inner in this case. 
The Member inner class have the reference of Outer class that is why it can access all 
the data members of Outer class including private.
*/
public class InnerClass {
private int data = 30;

class Inner {
void msg() {
System.out.println("data is " + data);
}
}
public static void main(String args[]) {
InnerClass obj = new InnerClass();
InnerClass.Inner in = obj.new Inner();
in.msg();
}
}

No comments:

Post a Comment