Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class definition inside method argument in Java?

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?

like image 893
Shailesh Tainwala Avatar asked Mar 03 '11 11:03

Shailesh Tainwala


People also ask

Can we define class inside method in Java?

In Java, we can write a class within a method and this will be a local type. Like local variables, the scope of the inner class is restricted within the method.

Can a class be defined inside a method?

You can define a local class inside any block (see Expressions, Statements, and Blocks for more information). For example, you can define a local class in a method body, a for loop, or an if clause.

Can we pass class objects as function arguments in Java?

Passing Object as Parameter in Function While creating a variable of class type, we only create a reference to an object. When we pass this reference to a function, the parameters that receive it will refer to the same object as that referred to by the argument.

What is method argument in Java?

Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order.


1 Answers

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).

like image 56
Jon Skeet Avatar answered Sep 22 '22 08:09

Jon Skeet