- Apache Spark 2.x for Java Developers
- Sourav Gulati Sumit Kumar
- 268字
- 2021-07-02 19:01:56
Anonymous inner classes
Anonymous inner classes are essentially inner classes in Java. They are called anonymous as they don't possess a name. They are declared and instantiated at the same time.
Anonymous inner classes are used whenever you need to provide the implementation of the interface or override the abstract method of a class. They are useful if the implementation of the interface or abstract class is needed only once.
Let's discuss it with the example of the FilenameFilter interface, which has been included in Java since JDK1.0.
Suppose you want to print all the files in a directory whose name ends with java.
The first approach is to create a class that implements the FilenameFilter interface as follows:
public class MyFileNameFilter implements FilenameFilter { @Override public boolean accept(File dir, String name) { return name.endsWith("java"); } }
Then, use the object of this class in your implementation as follows:
public class MyFilterImpl { public static void main(String[] args) { File dir = new File("src/main/java"); dir.list(new MyFileNameFilter()); } }
However, you may require the implementation of this interface only once in your code, so instead of creating a separate class you can provide the implementation of this interface anonymously as follows:
public class MyFilterImpl { public static void main(String[] args) { File dir = new File("src/main/java"); dir.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith("java"); } }); } }
This is an example of anonymous inner classes. The code might look weird at the time, but this is a very concise way of implementing an interface or abstract class if implementation is needed only once.
- 精通Nginx(第2版)
- JavaScript前端開發(fā)模塊化教程
- Delphi程序設(shè)計基礎(chǔ):教程、實驗、習(xí)題
- Python程序設(shè)計(第3版)
- Hands-On Data Structures and Algorithms with JavaScript
- 編寫整潔的Python代碼(第2版)
- iOS開發(fā)實戰(zhàn):從零基礎(chǔ)到App Store上架
- 軟件架構(gòu):Python語言實現(xiàn)
- QTP自動化測試進(jìn)階
- Microsoft Azure Storage Essentials
- Emotional Intelligence for IT Professionals
- Anaconda數(shù)據(jù)科學(xué)實戰(zhàn)
- Web開發(fā)的平民英雄:PHP+MySQL
- 大話代碼架構(gòu):項目實戰(zhàn)版
- 從零開始學(xué)UI設(shè)計·基礎(chǔ)篇