user13632019
user13632019

Reputation:

Difference between "ClassA object = new ClassA();" and "new ClassA();"?

I don't know if this has already been asked since I can't find it anywhere.

So, recently I came across this feature in IntelliJ IDEA where it says transform expressions.

Here is the picture:

enter image description here

What I want to know is that what is the difference between ClassA object = new ClassA(); and new ClassA();.

Is there any functional differences or anything else that may impact normal code functioning in any way?

Upvotes: 4

Views: 184

Answers (4)

Shan S
Shan S

Reputation: 678

If you use new ClassA() and don't do anything with it, that instance is unreachable unless you're storing it somehow, somewhere (for example, in a List). If it has any side effects, however (like printing), those side effects will still occur. If you use ClassA object = new ClassA();, you'll be able to use that specific instance later in the code due to the name binding.

You'd normally use new ClassA() when you want it to be anonymous because you don't need a long-standing reference. For example:

List<ClassA> instances = new LinkedList<>();
for (int i = 0; i < 100; i++) {
    instances.add(new ClassA());
}

or

void doSomethingWithClass(ClassA c) {
    // do something
}

doSomethingWithClass(new ClassA());

Upvotes: 1

Nafaz M N M
Nafaz M N M

Reputation: 1698

There is no difference. Two instances have been created for ClassA. one instance is called "object" and the other instance is "anonymous".

Upvotes: 0

S M Vaidhyanathan
S M Vaidhyanathan

Reputation: 360

By this statement, ClassA object = new ClassA(); , you are creating a reference. Whereas when you write new ClassA(); It is an anonymous object that you are creating. It is to be noted that If you have to use an object only once, an anonymous object is a good approach.

See more info about anonymous objects here

Upvotes: 0

Eran
Eran

Reputation: 393841

If your code contains a variable

ClassA object = new ClassA();

which you never use later in the code, you can eliminate the variable and the new ClassA() expression.

However, if creating an instance of ClassA() has some side effects relevant to your program (i.e., you need the constructor of ClassA to be executed even if you don't do anything with the created ClassA instance later), you can replace that statement with a statement that creates an instance without assigning it to a variable:

new ClassA();

Such a statement makes it clear that the created instance is not expected to be accessed later by following code.

However, both statements will function the same (though the first statement may result in a warning saying you declared a variable that you are not using).

Upvotes: 3

Related Questions