Home > OS >  Java: Object myObject = new Object() OR new Object()
Java: Object myObject = new Object() OR new Object()

Time:08-27

I am learning java and when I make an object I always do something like:

Object object = new Object();

I have seen some people in youtube videos doing this instead

new Object();

Could someone explain the difference between the two? Sorry, I couldn't find anything online.

CodePudding user response:

In both cases, an object is created, except that the former uses Object to store the newly created object, which can be used later. The latter simply creates objects and cannot be used later as variables.

Here is an example of using a newly created object:

Object object = new Object()
object = ...

CodePudding user response:

It's all about reusability. Reusability is one of the major advantages of Object Oriented Programming. Object object = new Object(); provides reusability as you can use the object instance, below anywhere after its declaration. But new Object() kind of declaration creates the instance of Object class in the particular line and it can not be reused in the below instances, as the created instance won't be stored in the heap memory of the application.

  •  Tags:  
  • java
  • Related