Showing posts with label Inner Class. Show all posts
Showing posts with label Inner Class. Show all posts

Tuesday 16 April 2013

What is ineer class in java? What are the types of inner class in java?



Inner class is a class defined inside other class and act like a member of the enclosing class.
There are two main types of inner classes –
  • Static member class
  • Inner class
    • Member class
    • Anonymous class
    • Local class
Static Member Class:-  A static member class behaves much like an ordinary top-level class, except that it can access the static members of the class that contains it. The static nested class can be accessed as the other static members of the enclosing class without having an instance of the outer class. The static class can contain non-static and static members and methods.
public class InnerClass {
      static class StaticInner {
            static int i = 9;
            int no = 6;

            private void method() {}
            public void method1() {}
            static void method2() {}
            final void method3() {}
      }
}

  The static inner class can be accessed from Outer Class in the following manner:
InnerClass.StaticInner  staticObj= new   InnerClass. StaticInner ();
No outer class instance is required to instantiate the nested static class because the static class is a static member of the enclosing class.
Non - static inner classes – classes associated with the object of the enclosing class. They also have further sub classed as
1. Member class - Classes declared outside a function (hence a "member") and not declared "static".
The member class can be declared as public, private, protected, final and abstract. E.g.

test1.InnerClass  xx = new test1().new InnerClass() ; //Access Member Class
2. Method local class – The inner class declared inside the method is called method local inner class. Method local inner class can only be declared as final or abstract. Method local class can only access global variables or method local variables if declared as final
3. Anonymous inner class - These are local classes which are automatically declared and instantiated in the middle of an expression.  Also, like local classes, anonymous classes cannot be public, private, protected, or static. They can specify arguments to the constructor of the superclass, but cannot otherwise have a constructor. They can implement only one interface or extend a class.
The class declared inside the body of a method without naming it is known as anonymous inner classes
Anonymous class cannot define any static fields, methods, or classes, except for static final constants.
Also, like local classes.