How to use anonymous inner classes in Java?

Java anonymous inner classes are a special way of defining a class directly while declaring and instantiating it, which can simplify coding and improve code readability.

The steps for using an anonymous inner class are as follows:

  1. Define an anonymous inner class as an implementation class of an interface or abstract class, or directly as a subclass of a class.
  2. fresh
  3. If the anonymous inner class implements an interface, you can directly implement the interface’s methods in the class implementing the interface.
  4. If an anonymous inner class inherits from a class, it can directly override the methods of the superclass in the subclass.

Here is an example code snippet using an anonymous inner class:

public class AnonymousInnerClassExample {
    
    public static void main(String[] args) {
        // 使用匿名内部类实现接口
        MyInterface myInterface = new MyInterface() {
            @Override
            public void method() {
                System.out.println("实现接口的匿名内部类");
            }
        };
        myInterface.method();
        
        // 使用匿名内部类继承类
        MyClass myClass = new MyClass() {
            @Override
            public void method() {
                System.out.println("继承类的匿名内部类");
            }
        };
        myClass.method();
    }
    
    // 定义接口
    public interface MyInterface {
        void method();
    }
    
    // 定义类
    public static class MyClass {
        public void method() {
            System.out.println("原始类");
        }
    }
}

The output result is:

实现接口的匿名内部类
继承类的匿名内部类

In the above code, the MyInterface interface and MyClass class were implemented using anonymous inner classes, with their corresponding methods overridden. An instance of the anonymous inner class was created in the main method, and its methods were called.

广告
Closing in 10 seconds
bannerAds