Summary of anonymous inner classes in java
Anonymous inner classes are inner classes without names
Because they have no names, anonymous inner classes can only be used once. They are usually used to simplify code writing
But there is a prerequisite for using anonymous inner classes: you must inherit one Parent class or implement an interface
Example 1: Do not use anonymous inner classes to implement abstract methods
abstract class Person { public abstract void eat(); } class Child extends Person { public void eat() { System.out.println("eat something"); } } public class Demo { public static void main(String[] args) { Person p = new Child(); p.eat(); } }
Running results: eat something
As you can see, we use Child to inherit the Person class, and then implement a Child instance, upcast it to a reference to the Person class
However, if the Child class here is only used once, wouldn't it be troublesome to write it as an independent class?
Anonymous inner classes are introduced at this time
Example 2: Basic implementation of anonymous inner classes
abstract class Person { public abstract void eat(); } public class Demo { public static void main(String[] args) { Person p = new Person() { public void eat() { System.out.println("eat something"); } }; p.eat(); } }
Run result: eat something
As you can see, we directly put the methods in the abstract class Person in curly brackets Implemented
This way you can omit the writing of a class
Moreover, anonymous inner classes can also be used on interfaces
Example 3: Using anonymous inner classes on interfaces
interface Person { public void eat(); } public class Demo { public static void main(String[] args) { Person p = new Person() { public void eat() { System.out.println("eat something"); } }; p.eat(); } }
Run results: eat something
By As can be seen from the above example, as long as a class is abstract or an interface, then the methods in its subclasses can be implemented using anonymous inner classes
The most common situation is in multi-threaded implementation, because it needs to be implemented Multi-threading must inherit the Thread class or inherit the Runnable interface
Example 4: Anonymous inner class implementation of the Thread class
public class Demo { public static void main(String[] args) { Thread t = new Thread() { public void run() { for (int i = 1; i <= 5; i++) { System.out.print(i + " "); } } }; t.start(); } }
Running results: 1 2 3 4 5
Example 5: Anonymous inner class implementation of the Runnable interface
public class Demo { public static void main(String[] args) { Runnable r = new Runnable() { public void run() { for (int i = 1; i <= 5; i++) { System.out.print(i + " "); } } }; Thread t = new Thread(r); t.start(); } }
Running results: 1 2 3 4 5

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Anonymous inner classes can cause memory leaks. The problem is that they hold a reference to the outer class, preventing the outer class from being garbage collected. Solutions include: 1. Use weak references. When the external class is no longer held by a strong reference, the garbage collector will immediately recycle the weak reference object; 2. Use soft references. The garbage collector will recycle the weak reference object when it needs memory during garbage collection. Only then the soft reference object is recycled. In actual combat, such as in Android applications, the memory leak problem caused by anonymous inner classes can be solved by using weak references, so that the anonymous inner class can be recycled when the listener is not needed.

Anonymous inner classes are special inner classes in Java that have no explicit name and are created through the new expression. They are mainly used to implement specific interfaces or extend abstract classes and are used immediately after creation. Common anonymous inner class design patterns include: Adapter pattern: converts one interface into another interface. Strategy Pattern: Defining and Replacement Algorithms. Observer pattern: Register observers and handle events. It is very useful in practical applications, such as sorting a TreeSet by string length, creating anonymous threads, etc.

Anonymous inner classes are used in Java as special inner classes that facilitate subclassing, simplifying code, and handling events (such as button clicks). Practical cases include: Event handling: Use anonymous inner classes to add click event listeners for buttons. Data transformation: Sort collections using Collections.sort method and anonymous inner class as comparator.

Anonymous inner classes are not suitable for use when: need to access private members, need multiple instances, need inheritance, need to access generic types

Anonymous inner class usage error: Accessing an out-of-scope variable using catching an undeclared exception in a non-thread-safe environment

The performance problem of anonymous inner classes is that they are recreated every time they are used, which can be optimized through the following strategies: 1. Store anonymous inner classes in local variables; 2. Use non-static inner classes; 3. Use lambda expressions. Practical tests show that lambda expression optimization has the best effect.

The lifetime of an anonymous inner class is determined by its scope: Method-local inner class: Valid only within the scope of the method that created it. Constructor inner class: bound to the outer class instance and released when the outer class instance is released. Static inner classes: loaded and unloaded at the same time as external classes.

Anonymous inner classes simplify the creation of multi-threaded code, eliminating the need for naming and enabling instant definition and use of thread classes. The main advantage is to simplify the code, while the limitation is that it cannot be extended. Use when you need to quickly create one or two threads. Keep the code short. If more complex logic is required, a separate class file should be created.
