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?
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With