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

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.

主站蜘蛛池模板: 山阴县| 红桥区| 怀集县| 楚雄市| 新郑市| 石阡县| 抚州市| 乐都县| 长宁县| 宁都县| 定西市| 鸡西市| 丰原市| 杨浦区| 蓝田县| 库车县| 达州市| 重庆市| 鲁甸县| 汶川县| 怀远县| 晋中市| 凯里市| 巴林左旗| 阜新| 右玉县| 芜湖市| 康定县| 三门县| 井研县| 化德县| 阿巴嘎旗| 图木舒克市| 阿合奇县| 潮州市| 普宁市| 五河县| 旬阳县| 西畴县| 巩义市| 凌源市|