- 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.
- 深入理解Bootstrap
- Vue.js入門與商城開發(fā)實戰(zhàn)
- Practical Data Science Cookbook(Second Edition)
- C語言程序設(shè)計
- Python金融數(shù)據(jù)分析
- Reactive Programming With Java 9
- SSM輕量級框架應(yīng)用實戰(zhàn)
- The HTML and CSS Workshop
- Swift語言實戰(zhàn)精講
- 大數(shù)據(jù)分析與應(yīng)用實戰(zhàn):統(tǒng)計機器學(xué)習(xí)之?dāng)?shù)據(jù)導(dǎo)向編程
- Lighttpd源碼分析
- Functional Python Programming
- Android技術(shù)內(nèi)幕(系統(tǒng)卷)
- TensorFlow.NET實戰(zhàn)
- Java程序設(shè)計基礎(chǔ)教程