11

I have come across Java code in this form for the first time:

object.methodA(new ISomeName() {
public void someMethod() {
//some code
}
});

Where ISomeName is an interface that has one method with the same signature as someMethod() above.

From what I can understand, we are defining a new nameclass class that implements ISomeName, creating an object of this class using default constructor and passing the object as an argument to methodA.

Is this right?

What is the name of this feature?

2
  • 2
    Good explanation here: stackoverflow.com/questions/3167427/… Commented Mar 3, 2011 at 11:43
  • (Note that if you extend a class here with a non-no-args constructor, then you can pass in arguments using the obvious syntax. But very rare.) Commented Mar 3, 2011 at 13:40

4 Answers 4

4

It's creating an anonymous class.

Note that within anonymous class, you can refer to final local variables from within the earlier code of the method, including final parameters:

final String name = getName();

Thread t = new Thread(new Runnable() {
    @Override public void run() {
        System.out.println(name);
    }
});
t.start();

The values of the variables are passed into the constructor of the anonymous class. This is a weak form of closures (weak because of the restrictions: only values are copied, which is why the variable has to be final).

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

Comments

1

this is called anonymous classes in Java. It means that you create anonymous class that implements ISomeName interface and is passed as argument to methodA.

Comments

1

It's called an Anonymous Class (PDF link).

Comments

1

This feature is called anonymous classes.

Comments

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.