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
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.