There are total 5 core ways to create objects in Java which are explained below with their example followed by bytecode of the line which is creating the object. However, lots of Apis are out there are which creates objects for us but these Apis will also are using one of these 5 core ways indirectly e.g. Spring BeanFactory.
If you will execute program given in the end, you will see method 1, 2, 3 uses the constructor to create the object while 4, 5 doesn’t call the constructor to create the object.
1. Using the new keyword
It is the most common and regular way to create an object and actually very simple one also. By using this method we can call whichever constructor we want to call (no-arg constructor as well as parametrised). Employee emp1 = new Employee();
0: new #19 // class org/programming/mitra/exercises/Employee
3: dup
4: invokespecial #21 // Method org/programming/mitra/exercises/Employee."":()V
2. Using Class.newInstance() method
We can also use the newInstance() method of the Class class to create objects, This newInstance() method calls the no-arg constructor to create the object.We can create objects by newInstance() in the following way.
Employee emp2 = (Employee) Class.forName("org.programming.mitra.exercises.Employee")
.newInstance();
Or
Employee emp2 = Employee.class.newInstance();
51: invokevirtual #70 // Method java/lang/Class.newInstance:()Ljava/lang/Object;
3. Using newInstance() method of Constructor class
Similar to the newInstance() method of Class class, There is one newInstance() method in the java.lang.reflect.Constructor class which we can use to create objects. We can also call a parameterized constructor, and private constructor by using this newInstance() method.Both newInstance() methods are known as reflective ways to create objects. In fact newInstance() method of Class class internally uses newInstance() method of Constructor class. That's why the later one is preferred and also used by different frameworks like Spring, Hibernate, Struts etc. To know the differences between both newInstance() methods read Creating objects through Reflection in Java with Example.
Constructor<Employee> constructor = Employee.class.getConstructor();
Employee emp3 = constructor.newInstance();
111: invokevirtual #80 // Method java/lang/reflect/Constructor.newInstance:([Ljava/lang/Object;)Ljava/lang/Object;
4. Using clone() method
Whenever we call clone() on any object JVM actually creates a new object for us and copy all content of the previous object into it. Creating an object using the clone method does not invoke any constructor.To use the clone() method on an object we need to implements Cloneable and define clone() method in it.
Employee emp4 = (Employee) emp3.clone();
162: invokevirtual #87 // Method org/programming/mitra/exercises/Employee.clone ()Ljava/lang/Object;
Java cloning is the most debatable topic in Java community and it surely does have its drawbacks but it is still the most popular and easy way of creating a copy of any object until that object is full filling mandatory conditions of Java cloning. I have covered cloning in details in a 3 article long Java Cloning Series which includes articles like Java Cloning And Types Of Cloning (Shallow And Deep) In Details With Example, Java Cloning - Copy Constructor Versus Cloning, Java Cloning - Even Copy Constructors Are Not Sufficient. Please go ahead and read them if you want to know more about cloning.
5. Using deserialization
Whenever we serialize and then deserialize an object JVM creates a separate object for us. In deserialization, JVM doesn’t use any constructor to create the object.To deserialize an object we need to implement the Serializable interface in our class.
ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));
Employee emp5 = (Employee) in.readObject();
261: invokevirtual #118 // Method java/io/ObjectInputStream.readObject:()Ljava/lang/Object;
As we can see in above bytecodes all 4 methods call get converted to invokevirtual (object creation is directly handled by these methods) except the first one which got converted to two calls one is new and other is invokespecial (call to the constructor).
I have discussed serialization and deserialization in more details in serialization series which includes articles like Everything You Need To Know About Java Serialization, How To Customize Serialization In Java By Using Externalizable Interface, How To Deep Clone An Object Using Java In Memory Serialization. Please go ahead and read them if you want to know more about serialization.
Example
Let’s consider an Employee class for which we are going to create the objectsclass Employee implements Cloneable, Serializable {
private static final long serialVersionUID = 1L;
private String name;
public Employee() {
System.out.println("Employee Constructor Called...");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return "Employee [name=" + name + "]";
}
@Override
public Object clone() {
Object obj = null;
try {
obj = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return obj;
}
}
In below Java program, we are going to create Employee objects in all 5 ways, you can also found the complete source code at Github.
public class ObjectCreation {
public static void main(String... args) throws Exception {
// By using new keyword
Employee emp1 = new Employee();
emp1.setName("Naresh");
System.out.println(emp1 + ", hashcode : " + emp1.hashCode());
// By using Class class's newInstance() method
Employee emp2 = (Employee) Class.forName("org.programming.mitra.exercises.Employee")
.newInstance();
// Or we can simply do this
// Employee emp2 = Employee.class.newInstance();
emp2.setName("Rishi");
System.out.println(emp2 + ", hashcode : " + emp2.hashCode());
// By using Constructor class's newInstance() method
Constructor<Employee> constructor = Employee.class.getConstructor();
Employee emp3 = constructor.newInstance();
emp3.setName("Yogesh");
System.out.println(emp3 + ", hashcode : " + emp3.hashCode());
// By using clone() method
Employee emp4 = (Employee) emp3.clone();
emp4.setName("Atul");
System.out.println(emp4 + ", hashcode : " + emp4.hashCode());
// By using Deserialization
// Serialization
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.obj"));
out.writeObject(emp4);
out.close();
//Deserialization
ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));
Employee emp5 = (Employee) in.readObject();
in.close();
emp5.setName("Akash");
System.out.println(emp5 + ", hashcode : " + emp5.hashCode());
}
}
This program will give the following output
Employee Constructor Called...
Employee [name=Naresh], hashcode : -1968815046
Employee Constructor Called...
Employee [name=Rishi], hashcode : 78970652
Employee Constructor Called...
Employee [name=Yogesh], hashcode : -1641292792
Employee [name=Atul], hashcode : 2051657
Employee [name=Akash], hashcode : 63313419
nice article.
ReplyDeleteThanks Pradip
DeleteWhile Deserialization, JVM uses a constructor to create aa object.
DeletePlease find two scenarios.
1. In our code, Employee class implements Serializable and there is no parent class, so Object class is parent class.
While Deserialization, JVM uses a Object class constructor to create an object.
2. If we create a new parent class and extend it in Employee class.
While Deserialization, JVM uses a Person class constructor to create an object.
Please find code sample.
class Person {
Person() {
System.out.println("Person Class");
}
}
class Employee extends Person implements Cloneable, Serializable {}
Output :
Person Class
Employee [name=Akash], hashcode : 63313419
I see it, I think this might be happening because of constructor chaining (all super class constructors are getting called according to hierarchy) which is actually part of object creation.
DeleteBut Employee class's constructor does not get called as you can see by the running the code with below classes
class Person {
Person() {
System.out.println("Person Class");
}
}
class Employee extends Person implements Cloneable, Serializable {
Employee(){
System.out.println("Employee Class");
}
}
how to create an object with a name given by the user in java
ReplyDeleteI believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
ReplyDeletejava training in chennai
I trying understand this phrase:
ReplyDelete"Java cloning is the most debatable topic in Java community and it surely does have its drawbacks but it is still the most popular and easy way of creating a copy of any object until that object is full filling mandatory conditions of Java cloning."
What author has means? Most interesting:
"until that object is full filling mandatory conditions of Java cloning"
About which mandatory we are talking about?
I don't understand that phrase at all ((:
"full filling mandatory conditions"
Thanks! @Hoz for expressing your concerns, If you read the link mentioned under the section `Using clone() method`, you will find out in order to call clone on a object your class have to implement Cloneable interface, should define a clone method of its own which should handle CloneNotSupportedException and call the clone() method of the superclass. And even after this much effort you will handle deep cloning separately. Please read the mentioned links for more details.
DeleteGood one
ReplyDeleteJava is an essential things to develop android application. Thanks for showing the different ways to create objects in java.
ReplyDeleteThanks!
DeleteThank you a lot, this was a great helo
ReplyDeleteNote that the class Employee could add a `cloneSerialized()` method that contains the Serialized cloning clode. We could clone an `Employee employee` by just using `employee_clone = employee.cloneSerialized()`
In India, a popular game of chance is called Satta
ReplyDeleteMatka. It entails anticipating the Indian national lottery's winning numbers. In India, a popular game of chance is called Satta Matka. Matching the final digits of the winning lotto numbers is how it is played.
When playing the dice game Satta Matka, the player must predict the number that will be revealed. The player has the option of placing a wager on either the number or a specific column.
ReplyDeleteIn India, many individuals like playing Satta matka. Farmers who used to wager on cattle and crops played the game during its inception in India. Satta matka is now played by Indians everywhere, especially those who are expatriates.
ReplyDeleteWelcome to JS Dolls, the premier destination for premium sex dolls for sale in 2022. We offer a wide selection of high-quality, realistic sex dolls for sale at unbeatable prices. Our dolls are perfect for people of all ages, genders, and sexual orientations. Whether you're looking for a companion to spice up your bedroom or a friend to share intimate moments with, we have the doll for you.
ReplyDeleteBest 2D & 3D animation software
ReplyDeleteThis is really very informative blog thanks for sharing ! Mobile app development company
ReplyDeleteOur IT management assignment help service goes beyond just providing solutions; we strive to ensure your complete satisfaction. We guarantee originality and authenticity in every assignment we deliver. Our writers conduct thorough research and utilize credible sources to create well-referenced and properly formatted papers.
ReplyDeleteNS Ventures offers real estate virtual tour services in India. With 360-degree virtual tours for real estate, you can provide potential buyers a genuine in-person experience of touring your property. This will put you in a fantastic position to draw more visitors and, subsequently, more customers.
ReplyDeleteNice post good work
ReplyDeletelndian Satta
Yalova
ReplyDeleteHatay
Muş
Bursa
Mersin
KAH1WQ
van
ReplyDeletekastamonu
elazığ
tokat
sakarya
İSJPVG
https://titandijital.com.tr/
ReplyDeletemalatya parça eşya taşıma
bilecik parça eşya taşıma
antalya parça eşya taşıma
hakkari parça eşya taşıma
A3DİBR
Whey protein is rapidly digested and absorbed by the body, which makes it an excellent choice for a post-workout shake. It can quickly supply your muscles with the necessary nutrients for recovery and growth and for more info visit - Best Pre Workout in India
ReplyDeletevan evden eve nakliyat
ReplyDeletesivas evden eve nakliyat
çankırı evden eve nakliyat
bartın evden eve nakliyat
erzincan evden eve nakliyat
JW4QC
FECA4
ReplyDeleteAdana Şehir İçi Nakliyat
Çerkezköy Mutfak Dolabı
Altındağ Boya Ustası
Çanakkale Şehir İçi Nakliyat
Çerkezköy Cam Balkon
Edirne Şehir İçi Nakliyat
Çerkezköy Kurtarıcı
Pancakeswap Güvenilir mi
Şırnak Parça Eşya Taşıma
C2FDB
ReplyDeleteArdahan Şehirler Arası Nakliyat
Giresun Şehir İçi Nakliyat
Rize Şehir İçi Nakliyat
Baby Doge Coin Hangi Borsada
Probit Güvenilir mi
Ankara Parça Eşya Taşıma
Çerkezköy Asma Tavan
Çerkezköy Oto Lastik
Kırıkkale Şehirler Arası Nakliyat
24955
ReplyDeletekadınlarla sohbet
Uşak Canli Sohbet Chat
kırklareli bedava sohbet odaları
rize mobil sohbet odaları
maraş ücretsiz sohbet
rize canlı görüntülü sohbet siteleri
canli sohbet chat
Düzce Sesli Sohbet Odası
görüntülü sohbet
2AC3C
ReplyDeleteKripto Para Çıkarma Siteleri
Clysterum Coin Hangi Borsada
Dxgm Coin Hangi Borsada
Coin Nasıl Kazılır
Tumblr Takipçi Satın Al
Sohbet
Binance Referans Kodu
Binance Referans Kodu
Tumblr Beğeni Hilesi
B0397
ReplyDeletepoocoin
trust wallet
dextools
quickswap
dcent
pancakeswap
uniswap
safepal
arbitrum
D58CD
ReplyDeletebitexen
gate io
btcturk
referans kodu
bkex
telegram kripto para
okex
kredi kartı ile kripto para alma
kripto ne demek
93B06
ReplyDeletecoin nereden alınır
referans kimligi nedir
bitcoin hangi bankalarda var
canlı sohbet ücretsiz
bitcoin hesabı nasıl açılır
telegram kripto grupları
btcturk
coinex
kripto telegram
A61B4
ReplyDeletegate io
referans kodu binance
referans kimliği
toptan mum
kripto para kanalları telegram
aax
binance
canli sohbet
bitcoin giriş
Rc King Mass gainer, which contains complex carbs like oats and maltodextrin, replenishes glycogen stores after exercise, increasing muscle regeneration and reducing fatigue.
ReplyDeleteImprove your online presence with our top-notch SEO services in San Francisco. Our skilled experts create custom plans to improve your website's exposure and draw in targeted leads. With our results-driven strategy, you can outperform your competitors and experience unmatched growth. KNOW MORE : SEO services in San Francisco
ReplyDeleteThe great flavor and texture of Avvatar alpha whey protein make it a pleasure to consume. Available in a variety of mouthwatering flavors, this protein powder is a real delight for your taste buds.
ReplyDeleteSmile Tech is a well-respected provider of SEO services in Seattle for companies trying to increase their online visibility. With years of expertise and a group of committed SEO specialists, Smile Tech has assisted many Seattle-area companies and other companies in achieving their digital marketing objectives. KNOW MORE: Seo service in Seattle
ReplyDelete84A98
ReplyDeletemexc
canlı sohbet odaları
binance
binance 100 dolar
btcturk
kucoin
mobil 4g proxy
bingx
bitcoin giriş
Helperji's Noida commercial cleaning services have been a game changer for our business. Their thorough approach and attention to customer satisfaction distinguishes them in the industry.
ReplyDeleteA724E
ReplyDeletegüvenilir show