I’m trying to understand arguments with respect to anonymous classes. The examples in books I’ve seen either don’t have arguments or else don’t explain them well. Here’s the code (from Java in a Nutshell 2nd edition example 5-8 and yes I know it’s old :-)…
import java.io.*;
//Print out all the *.java files in the directory.
public static void main(String[] args)
{
File f = new File(args[0]);
String[] list = f.list(new FilenameFilter() {
public boolean accept(File f, String s) {
return s.endsWith(".java");
}
});
for (int i = 0; i < list.length; i++)
System.out.println(list[i]);
}
}
My questions is how the filename f gets applied to the ‘File f’ argument of ‘accept’, and also where does the ‘String s’ argument come from? Why does the ‘accept’ method get called, is it from the FilenameFilter constructor perhaps?
Thanks!
if you take a look into the source files of the java api, you will find following in File.java:
which calls the accept method of the given filename filter. String s is in your example
names[i].list()returns an array of strings naming the files and directories in the directory denoted by the files pathname.to explain your code:
calls the list method of the File class (see above) with a new anonymous class of the FilenameFilter interface with an implementation of the accept method.