An inner class is simply a class inside another class. There are four kinds.
1. Nested inner class
An inner class can access the contents of its outer class. You use the inner class by creating its object inside the outer class directly — but the outer class cannot access the inner class’s contents directly unless it has created an object of it.
class OuterNew { int x = 10; InnerNew i = new InnerNew();
class InnerNew { int y = 20; public void innerDisplay() { System.out.println(x + " " + y); } } public void outerDisplay() { i.innerDisplay(); System.out.println(i.y); }}
public class NestedInner { public static void main(String[] args) { OuterNew o = new OuterNew(); o.outerDisplay(); OuterNew.InnerNew oi = new OuterNew().new InnerNew(); oi.innerDisplay(); }}A slightly simpler version of the same idea:
class Outer { int x = 10;
class Inner { int y = 20;
void innerDisplay() { System.out.println(x); System.out.println(y); } } void outerDisplay() { Inner i = new Inner(); i.innerDisplay(); System.out.println(i.y); }}
public class NestedInnerClass { public static void main(String[] args) { Outer o = new Outer(); o.outerDisplay(); Outer.Inner i = new Outer().new Inner(); }}2. Local inner class
A class defined inside a method of the outer class, useful only inside that method. If you want a class to inherit from another class or implement an interface, but it’s only useful within one method, define it as a local inner class there.
3. Anonymous inner class
A class defined during the definition of an object. If you need to implement an interface with limited usage, you don’t have to write a separate named class and create its object — you can use an anonymous inner class instead.
abstract class My { abstract void display();}
class AnonOuter { public void meth() { My m = new My() { // My has been defined and overridden here, so it's become a concrete class — // but it has no name, hence "anonymous class" public void display() { System.out.println("Hello"); } }; m.display(); }}4. Static inner class
These are the static members of an outer class. Objects of a static inner class can be created directly, without creating an object of the outer class first.