官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 贵德县| 化州市| 南溪县| 鞍山市| 满洲里市| 大余县| 南陵县| 墨江| 建始县| 沙坪坝区| 萨嘎县| 中方县| 陈巴尔虎旗| 新兴县| 满洲里市| 昭平县| 丰顺县| 德兴市| 财经| 徐州市| 来宾市| 曲靖市| 安图县| 黎平县| 达孜县| 绥棱县| 彭州市| 吴川市| 中牟县| 小金县| 临潭县| 唐河县| 双流县| 荣成市| 北流市| 阳新县| 会理县| 思茅市| 成都市| 吉林省| 香港 |