2

can any one please help me understand this code block of java

String [] files= file.list(new FilenameFilter() {
    @Override           
    public boolean accept(File dir, String name) {
        // TODO Auto-generated method stub
        return true;            
    }
});

This is just example i need to understand the concept of new instance with override method inside method parameter.

I understand what this code do but i need to understand the concept*

3

4 Answers 4

0

Take a look at the documentation of File.list(FilenameFilter filter).

It takes a FilenameFilter as argument which in turn has method

boolean accept(File dir, String name)

You want to pass a new FilenameFilter to the method and you do that by passing it in as an anonymous class and overriding the accept method in the anonymous class.

Sign up to request clarification or add additional context in comments.

Comments

0

Consider you have a method with an interface or an abstract class as a parameter. If you call this method, you have to pass a concrete instance of the specified type. One possibility is then, to create an instance inside the parameter. This is called anonymous class.

You should do this only when you need this class just once.

Comments

0

If you check in the actual implementation of the list() in java.io.File it look like this.

    public String[] list(FilenameFilter filter) {
    String names[] = list();
    if ((names == null) || (filter == null)) {
        return names;
    }
    List<String> v = new ArrayList<>();
    for (int i = 0 ; i < names.length ; i++) {
        if (filter.accept(this, names[i])) {
            v.add(names[i]);
        }
    }
    return v.toArray(new String[v.size()]);
}

That method is expecting any instance which implements FilenameFilter. And what it does inside File.list() method is it calls to the accept() of the filter parameter. And which actually executes the original implementation of the caller. So that mean the overridden method content you have provided in this case.

Comments

-2

This is called Anonymous Inner Class

A class that have no name is known as anonymous inner class in java. It should be used if you have to override method of class or interface.

1 Comment

It's just anonymous class. Not inner class. Inner classes and anonymous classes are differents. Of course, you can have a class which is both at a time but as far as we know this is not the case here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.