javainterfaceabstract-methods

Overridden interface method that has parameters that are never used


New to Java coming from C++/Python and I found this in code today (not exactly this but similar [cant share code]):

File dir = new File("/home");
File[] files= dir.listFiles(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".txt");
    }
});

When looking at source of listFiles, filter is passed this representative of the reference to dir. But in its implementation its not used at all, only name is. When it comes implementing interfaces in Java, is this common place to have an abstract method with "potentially used" parameters, but they aren't required to be used? In C++/Python my linters would be going bonkers saying parameters are unused and can be removed.

Why not have multiple methods then for the interface?

@FunctionalInterface
public interface FilenameFilter {
    /**
     * Tests if a specified file should be included in a file list.
     *
     * @param   dir    the directory in which the file was found.
     * @param   name   the name of the file.
     * @return  {@code true} if and only if the name should be
     * included in the file list; {@code false} otherwise.
     */
    boolean accept(File dir, String name);

    /**
     * Tests if a specified file should be included in a file list.
     *
     * @param   name   the name of the file.
     * @return  {@code true} if and only if the name should be
     * included in the file list; {@code false} otherwise.
     */
    boolean accept(String name);
}

Solution

  • Why not have multiple methods then for the interface?

    FilenameFilter is a functional interace and in functional interface you can't have more than 1 abstract method. Had it not been a functional interface, you could have overloaded abstract method, but then you wouldn't be able to use lambda expression in your code.

    Secondly, the fact that you are not using one parameter is an implementation detail! There might be another implementation in code somewhere else that would use it.