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

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.

主站蜘蛛池模板: 黄大仙区| 大竹县| 博罗县| 肥城市| 海晏县| 建湖县| 聂拉木县| 彭泽县| 云梦县| 揭西县| 亚东县| 平谷区| 德保县| 德昌县| 永胜县| 合作市| 略阳县| 云林县| 鄂尔多斯市| 奇台县| 南阳市| 乌拉特中旗| 高唐县| 阳泉市| 灵寿县| 宣威市| 社旗县| 江油市| 昌江| 讷河市| 阿拉尔市| 普定县| 赤城县| 卢氏县| 宝鸡市| 洮南市| 桦甸市| 商丘市| 桓仁| 安徽省| 曲松县|