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

MDZS is laden with buddhist references. As a South Asian person, and history buff, it is so interesting to see how Buddhism, which originated from India, migrated, flourished & changed in the context of China. Here's some research (🙏🏼 @starkjeon for CN insight + citations)

1. LWJ’s sword Bichen ‘is likely an abbreviation for the term 躲避红尘 (duǒ bì hóng chén), which can be translated as such: 躲避: shunning or hiding away from 红尘 (worldly affairs; which is a buddhist teaching.) (
https://t.co/zF65W3roJe) (abbrev. TWX)

2. Sandu (三 毒), Jiang Cheng’s sword, refers to the three poisons (triviṣa) in Buddhism; desire (kāma-taṇhā), delusion (bhava-taṇhā) and hatred (vibhava-taṇhā).

These 3 poisons represent the roots of craving (tanha) and are the cause of Dukkha (suffering, pain) and thus result in rebirth.

Interesting that MXTX used this name for one of the characters who suffers, arguably, the worst of these three emotions.

3. The Qian kun purse “乾坤袋 (qián kūn dài) – can be called “Heaven and Earth” Pouch. In Buddhism, Maitreya (मैत्रेय) owns this to store items. It was believed that there was a mythical space inside the bag that could absorb the world.” (TWX)