Question

In the Java7 API reference(Java API 7) there's a function list() of File class that has the signature:

public String[] list(FilenameFilter filter)

where FilenameFilter is an interface. Suppose the use of this function in a program is something like below:

String[] list = new File(directory).list(new FilenameFilter() {

     @Override
     public boolean accept(File f, String s) 
     {
        return s.endsWith(".java"); 
     } 
});

As you can see we are instantiating an interface anonymously.

Please correct me if I'm wrong but is instantiating an interface valid in Java?

The reason I'm asking this because I thought interfaces are not instantiable(because interfaces don't have constructors) and for using an interface you have to implement that interface by a class. Then how's that possible that we are instantiating an interface without implementing by a class here?

Can anyone kindly help me find the error in my logic?

Was it helpful?

Solution

You are not instantiating an interface. You are instantiating an anonymous class, which implements that interface.

Assuming, the code posted above is in the file Foo.java, then you will see the following output by the compiler:

  1. Foo.class
  2. Foo$1.class

where Foo.class is obviously the compiled Foo class and Foo$1.class is the compiled anonymous class which you used in the code.

You'll find the specifics in the Java Language Specification, Chapter 15.9.5. Anonymous Class Declarations

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top