Why first way is correct, but second isn't?
First way:
new Object() { public void a() { /*code*/ } }.a();
Second way:
Object object = new Object() { public void a() { /*code*/ } }; object.a();
And where can I find more information about it?
Creating an Object Declaration − A variable declaration with a variable name with an object type. Instantiation − The 'new' keyword is used to create the object. Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.
A method declaration can provide more information about the method, including the return type of the method, the number and type of the arguments required by the method, and which other classes and objects can call the method. The next table shows all possible elements of a method declaration.
When you create an object, you are creating an instance of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object.
java.lang.Object
has no a
methods declared (2), while the anonymous class returned by the class instance creation expression new Object() { public void a() {} }
does (1).
Use Java 10's local variable type inference (var
) to make the second option as valid as the first one.
var object = new Object() { public void a() {} }; object.a();
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