Two different ways to implement an interface in java


By providing a concrete class

package com.mob;
import java.io.File;import java.io.FileFilter;
public class JavaFileFIlter implements FileFilter {

    @Override    public boolean accept (File file) {
        return file.getName().endsWith(".png");    }
}

This implements FileFilter which in this case is used to filter .png files


package com.mob;

import java.io.File;

public class FileFilterExample {

    public static void main (String[] args) {
        JavaFileFIlter javaFileFIlter = new JavaFileFIlter();
        File dir = new File("C:\\Madhu Personal");
        File[] files = dir.listFiles(javaFileFIlter);

        for (int i = 0; i< files.length; i++) {
            System.out.println(files[i].getName());
        }
    }
}

By writing an anonymous class

package com.mob;

import java.io.File;
import java.io.FileFilter;

public class FileFilterExample1 {

    public static void main (String[] args) {

        FileFilter fileFilter = new FileFilter() {
            @Override
            public boolean accept (File file) {
                return file.getName().endsWith(".png");
            }
        };

        File dir = new File("C:\\Madhu Personal");
        File[] files = dir.listFiles(fileFilter);

        for (int i = 0; i< files.length; i++) {
            System.out.println(files[i].getName());
        }
    }
}


Hope this helps:)

No comments:

 Python Basics How to check the version of Python interpreter mac terminal

Popular in last 30 days