Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of instantiating an object and not assigning it to a variable in Java?

Tags:

java

What is the use of the new keyword when you don't assign the resulting object to a reference?

here is sample.

public static void main(String[] args) {ample.
    Display display = new Display();

    new SWTApp(display);

    display.dispose();
}
like image 679
Yrais Avatar asked Dec 04 '22 02:12

Yrais


2 Answers

In your case, most probably, the constructor has a side-effect (launching the application in a thread?) and you are exclusively interested in that side-effect.

Look at it like an ugly way of invoking a method.

like image 59
akappa Avatar answered May 20 '23 22:05

akappa


Presumably in this case the constructor for SWTApp actually runs the application until it's closed. That doesn't sound like a great design to me, but there's nothing in the language to actually prevent it.

like image 33
Jon Skeet Avatar answered May 20 '23 22:05

Jon Skeet