首页 > 代码库 > JAVA内部类

JAVA内部类

JAVA中的内部类有成员内部类、静态内部类、局部内部类和匿名内部类。

public class OuterClass {
    private int i = 1;
    private static int j = 2;
    
    //成员内部类
    class InnerClass1 {
        public void print() {
            System.out.println("InnerClass1 print:" + i);
        }
    }
    
    //静态内部类
    static class InnerClass2 {
        public void print() {
            System.out.println("InnerClass2 print:" + j);
        }
    }
    
    public static void main(String[] args) {
        OuterClass.InnerClass1 inner1 = new OuterClass().new InnerClass1();
        inner1.print();
        OuterClass.InnerClass2 inner2 = new OuterClass.InnerClass2();
        inner2.print();
        //局部内部类
        class InnerClass3 {
            public void print() {
                System.out.println("InnerClass3 print:" + j);
            }
        }
        InnerClass3 inner3 = new InnerClass3();
        inner3.print();
        //匿名内部类
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("InnerClass4 print:" + j);
            }
        }).start();
    }
}

 

JAVA内部类