Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a method when creating an object

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?

like image 857
Sekobune Avatar asked Dec 28 '18 15:12

Sekobune


People also ask

How do you declare an object?

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.

What is declaring method?

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.

Which method gets called when you create an object?

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.


1 Answers

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(); 
like image 147
Andrew Tobilko Avatar answered Sep 23 '22 17:09

Andrew Tobilko