Five Different Ways to Create Objects in Java

a thread...

1. Using a new keyword.

It's the most popular one. We create an object by using a new operator followed by a constructor call.

Eg:
2. Using the newInstance() method of class "Class":

Eg:
3️. Using the newInstance() method in class "Constructor":

Eg:
Note:

Both the above ways (Shown in 2 and 3),
are known as reflective ways of creating objects.

Fun-fact:

Class's newInstance() method internally uses Constructor's newInstance() method.
4️. Using "Object" class clone() method

The clone() method creates a copy of an existing object.

The clone() method is part of the "Object" class which returns a clone object.

Eg:
When using the clone() method:

Always Remember,

1. The "Cloneable" interface is implemented.
2. The clone() method must be overridden with other classes.
3. Inside the clone() method, the class must call super.clone().
5️. Using Deserialization:

When we deserialize any object then JVM creates a new object internally.

For this, we need to implement the Serializable interface.

Eg:
Conclusion:

We've seen all five ways to create Objects in Java:

1. Using a new keyword.
2. Using Class.newInstance() method
3️. Using Constructor.newInstance() method
4️. Using Object.clone() method
5️. Using Deserialization

Thanks for reading!

More from Vikas Rajput

You May Also Like

https://t.co/6cRR2B3jBE
Viruses and other pathogens are often studied as stand-alone entities, despite that, in nature, they mostly live in multispecies associations called biofilms—both externally and within the host.

https://t.co/FBfXhUrH5d


Microorganisms in biofilms are enclosed by an extracellular matrix that confers protection and improves survival. Previous studies have shown that viruses can secondarily colonize preexisting biofilms, and viral biofilms have also been described.


...we raise the perspective that CoVs can persistently infect bats due to their association with biofilm structures. This phenomenon potentially provides an optimal environment for nonpathogenic & well-adapted viruses to interact with the host, as well as for viral recombination.


Biofilms can also enhance virion viability in extracellular environments, such as on fomites and in aquatic sediments, allowing viral persistence and dissemination.