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

**Thread on Bravery of Sikhs**
(I am forced to do this due to continuous hounding of Sikh Extremists since yesterday)

Rani Jindan Kaur, wife of Maharaja Ranjit Singh had illegitimate relations with Lal Singh (PM of Ranjit Singh). Along with Lal Singh, she attacked Jammu, burnt - https://t.co/EfjAq59AyI


Hindu villages of Jasrota, caused rebellion in Jammu, attacked Kishtwar.

Ancestors of Raja Ranjit Singh, The Sansi Tribe used to give daughters as concubines to Jahangir.


The Ludhiana Political Agency (Later NW Fronties Prov) was formed by less than 4000 British soldiers who advanced from Delhi and reached Ludhiana, receiving submissions of all sikh chiefs along the way. The submission of the troops of Raja of Lahore (Ranjit Singh) at Ambala.

Dabistan a contemporary book on Sikh History tells us that Guru Hargobind broke Naina devi Idol Same source describes Guru Hargobind serving a eunuch
YarKhan. (ref was proudly shared by a sikh on twitter)
Gobind Singh followed Bahadur Shah to Deccan to fight for him.


In Zafarnama, Guru Gobind Singh states that the reason he was in conflict with the Hill Rajas was that while they were worshiping idols, while he was an idol-breaker.

And idiot Hindus place him along Maharana, Prithviraj and Shivaji as saviours of Dharma.