Java inner class

Time:2020-3-22

Access rules for inner classes:

1. Internal classes can directly access members in external classes, including private.

The reason why you can directly access members in an external class is that the internal class holds a reference to an external class. Format: external class. This

2. To access internal classes, external classes must establish internal class objects.

3. Internal classes can be modified by member modifiers when they are in member positions. For example, private: encapsulates internal classes in external classes. Static: internal classes have the feature of static.

public class InnerClassDemo {
    public static void main(String[] args) {
        //Access method 1:
        Outer outer = new Outer();
        outer.method();
        //Access method 2:
        Outer.Inner in = new Outer().new Inner();
        in.function();
    }
}

class Outer{
    private int x = 4;
    class Inner{
        private int x = 5;
        void function(){
            int x = 6;
            System.out.println("inner:"+x);//6
            System.out.println("inner:"+this.x);//5
            System.out.println("inner:"+Outer.this.x);//4
        }
    }
    void method(){
        Inner in = new Inner();
        in.function();
    }
}

  4. When the inner class is statically decorated, it can only directly access the static decorated members of the outer class, which has access limitations.

   5.

public class InnerClassDemo {
    public static void main(String[] args) {
        new Outer.Inner().function();
    }
}

class Outer{
    private static int x = 4;
    static class Inner{
        void function(){
            System.out.println("inner:"+x);
        }
    }
    void method(){
        Inner in = new Inner();
        in.function();
    }
}
public class InnerClassDemo {
    public static void main(String[] args) {
        Outer.Inner.function();
    }
}

class Outer{
    private static int x = 6;
    static class Inner{
        static void function(){
            System.out.println("inner:"+x);
        }
    }
    void method(){
        Inner in = new Inner();
        in.function();
    }
}

  6. When a static member is defined in an inner class, the inner class must be static.

When a static method in an external class accesses an internal class, the internal class must also be static.