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

#தினம்_ஒரு_திருவாசகம்
தொல்லை இரும்பிறவிச் சூழும் தளை நீக்கி
அல்லல் அறுத்து ஆனந்தம் ஆக்கியதே – எல்லை
மருவா நெறியளிக்கும் வாதவூர் எங்கோன்
திருவாசகம் என்னும் தேன்

பொருள்:
1.எப்போது ஆரம்பித்தது என அறியப்படமுடியாத தொலை காலமாக (தொல்லை)

2. இருந்து வரும் (இரும்)


3.பிறவிப் பயணத்திலே ஆழ்த்துகின்ற (பிறவி சூழும்)

4.அறியாமையாகிய இடரை (தளை)

5.அகற்றி (நீக்கி),

6.அதன் விளைவால் சுகதுக்கமெனும் துயரங்கள் விலக (அல்லல் அறுத்து),

7.முழுநிறைவாய்த் தன்னுளே இறைவனை உணர்த்துவதே (ஆனந்த மாக்கியதே),

8.பிறந்து இறக்கும் காலவெளிகளில் (எல்லை)

9.பிணைக்காமல் (மருவா)

10.காக்கும் மெய்யறிவினைத் தருகின்ற (நெறியளிக்கும்),

11.என் தலைவனான மாணிக்க வாசகரின் (வாதவூரெங்கோன்)

12.திருவாசகம் எனும் தேன் (திருவா சகமென்னுந் தேன்)

முதல்வரி: பிறவி என்பது முன்வினை விதையால் முளைப்பதோர் பெருமரம். அந்த ‘முன்வினை’ எங்கு ஆரம்பித்தது எனச் சொல்ல இயலாது. ஆனால் ‘அறியாமை’ ஒன்றே ஆசைக்கும்,, அச்சத்துக்கும் காரணம் என்பதால், அவையே வினைகளை விளைவிப்பன என்பதால், தொடர்ந்து வரும் பிறவிகளுக்கு, ‘அறியாமையே’ காரணம்

அறியாமைக்கு ஆரம்பம் கிடையாது. நமக்கு ஒரு பொருளைப் பற்றிய அறிவு எப்போதிருந்து இல்லை? அதைச் சொல்ல முடியாது. அதனாலேதான் முதலடியில், ஆரம்பமில்லாத அஞ்ஞானத்தை பிறவிகளுக்குக் காரணமாகச் சொல்லியது. ஆனால் அறியாமை, அறிவின் எழுச்சியால், அப்போதே முடிந்து விடும்.