How to define inner classes in Java?

In Java, it is possible to create inner classes by defining another class inside a class. Inner classes have access to the member variables and methods of the outer class, including private members.

The syntax for defining an inner class is as follows:

class OuterClass {
    // 外部类的成员变量和方法
    
    class InnerClass {
        // 内部类的成员变量和方法
    }
}

In the above code, OuterClass is the outer class, and InnerClass is the inner class.

Internal classes can be divided into four types: member inner classes, local inner classes, anonymous inner classes, and static inner classes.

  1. Member inner class: A member inner class is a class defined within another class. It has the same scope as the outer class and can access all members of the outer class. To create an object of a member inner class, you must first create an object of the outer class.
class OuterClass {
    // 外部类的成员变量和方法
    
    class InnerClass {
        // 内部类的成员变量和方法
    }
    
    public static void main(String[] args) {
        OuterClass outer = new OuterClass(); // 创建外部类的对象
        InnerClass inner = outer.new InnerClass(); // 创建内部类的对象
    }
}
  1. last
class OuterClass {
    // 外部类的成员变量和方法
    
    public void method() {
        // 方法内的局部变量
        final int x = 10;
        
        class LocalInnerClass {
            // 局部内部类的成员变量和方法
            public void printX() {
                System.out.println(x); // 可以访问外部类的成员变量
            }
        }
        
        LocalInnerClass inner = new LocalInnerClass(); // 创建局部内部类的对象
        inner.printX(); // 调用局部内部类的方法
    }
}
  1. Anonymous inner class: An anonymous inner class is an inner class without a name. It is typically used to implement an interface or extend a class and is only used once.
interface MyInterface {
    void doSomething();
}

class OuterClass {
    // 外部类的成员变量和方法
    
    public void method() {
        MyInterface inner = new MyInterface() {
            // 匿名内部类的实现
            public void doSomething() {
                // 实现接口方法的具体逻辑
            }
        };
        
        inner.doSomething(); // 调用接口方法
    }
}
  1. Static inner class: A static inner class is a class defined within another class that operates independently of instances of the external class and can directly access static members of the external class.
class OuterClass {
    // 外部类的静态成员变量和方法
    
    static class StaticInnerClass {
        // 静态内部类的成员变量和方法
    }
    
    public static void main(String[] args) {
        StaticInnerClass inner = new StaticInnerClass(); // 创建静态内部类的对象
    }
}
bannerAds