Anonymous inner classes are inner classes defined when creating an instance without an explicit name. Syntax: new 6fbafa35b4f73740ce9fc2c7d0dbbcca() { // Anonymous inner class body}. Advantages: simplicity, code reuse, local scope. Disadvantages: poor readability and difficulty in debugging. Practical examples include overriding anonymous classes and implementing anonymous interfaces.
Java Anonymous Inner Class Creation Guide
What is an anonymous inner class?
Anonymous inner class is an inner class defined when creating an instance. They have no explicit name and are often used to override or implement a class or interface on a short notice.
Creating anonymous inner classes
To create anonymous inner classes in Java, use the following syntax:
new <基类或接口名>() { // 匿名内部类体 };
The base class or interface name is anonymous A class or interface from which an inner class will inherit or implement. The class body contains the definitions of the methods and fields of the anonymous inner class.
Practical case
1. Override anonymous class
Use anonymous inner class to override Runnable
class The run()
method:
Thread thread = new Thread(new Runnable() { @Override public void run() { System.out.println("匿名内部类线程运行"); } }); thread.start();
2. Implement the anonymous interface
Use the anonymous inner class to implement the Comparator
interface:
List<String> strings = new ArrayList<>(); Comparator<String> comparator = new Comparator<>() { @Override public int compare(String s1, String s2) { return s1.length() - s2.length(); } }; strings.sort(comparator);
Advantages
Disadvantages
The above is the detailed content of How to create anonymous inner classes in Java?. For more information, please follow other related articles on the PHP Chinese website!