• Inner class format

    public class Outer {
      public class Inner {
      }
    }
    Copy the code
  • Inner class access features

    An inner class can access members of an outer class directly, including private ones. To access members of an inner class, an outer class must create objects

    Public class Outer {private int num = 10; Public class Inner {// Inner class method public void show() {system.out.println (num); Public void innerShow() {Inner I = new Inner(); i.show(); }}Copy the code
    • Use inner classes in other classes
    Inner i = new Outer().new Inner();
    i.show();
    
    Outer o = new Outer();
    o.innerShow();
    Copy the code
  • Local inner class

    A local inner class is a class defined in a method, so it cannot be used directly outside the method. You need to create objects and use them inside the method. The class can directly access the members of the external class, and can access local variables inside the method

    Public class Outer {private int num = 10; Public void innerShow() {// Inner class Inner {// Inner class method public void show() {system.out.println (num); Inner I = new Inner(); i.show(); }}Copy the code
  • Anonymous inner class

    Public class Outer {private int num = 10; Public void innerShow() {// New Inner() {// public void innerShow() {// system.out.println (num); // } // }.show(); Inner i = new Inner() { public void show() { System.out.println(num); }}; i.show(); }}Copy the code