5 Different Ways To Create Objects in Java - DZone Java
5 Different Ways To Create Objects in Java - DZone Java
[New Guide] Download the 2018 Guide to IoT: Harnessing Device Data
Download Guide
Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach.
Download white paper now!
Being Java developers, we usually create lots of objects daily, but we always use dependency management
systems e.g. Spring to create these objects. However, there are more ways to create objects, which we will
study in this article.
There are five total ways to create objects in Java, which are explained below with their examples
followed by bytecode of the line which is creating the object.
If you will execute program given in 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.
2 3: dup
Or
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 differences
between both newInstance() methods read Creating objects through Reflection in Java with Example.
To use clone() method on an object we need to implement Cloneable and define the clone() method in it.
https://dzone.com/articles/5-different-ways-to-create-objects-in-java-with-ex 2/7
4/28/2018 5 Different Ways to Create Objects in Java - DZone Java
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 (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), go ahead and read them if you want to know more about cloning.
5. Using deserialization:
Whenever we serialize and deserialize an object, the JVM creates a separate object for us. In
deserialization, the JVM doesn’t use any constructor to create the object.
As we can see in the above bytecode snippets, all 4 methods are called and 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 constructor).
Example
Let’s consider an Employee class for which we are going to create the objects:
2
3 private static final long serialVersionUID = 1L;
4
5 private String name;
6
7 public Employee() {
9 }
10
11 public String getName() {
12 return name;
13 }
14
15 public void setName(String name) {
16 this.name = name;
}
https://dzone.com/articles/5-different-ways-to-create-objects-in-java-with-ex 3/7
4/28/2018 5 Different Ways to Create Objects in Java - DZone Java
17 }
18
19 @Override
22 int result = 1;
24 return result;
25 }
26
27 @Override
29 if (this == obj)
30 return true;
31 if (obj == null)
32 return false;
33 if (getClass() != obj.getClass())
34 return false;
36 if (name == null) {
37 if (other.name != null)
38 return false;
39 } else if (!name.equals(other.name))
40 return false;
41 return true;
42 }
43
44 @Override
47 }
48
49 @Override
51
52 Object obj = null;
53 try {
54 obj = super.clone();
55 } catch (CloneNotSupportedException e) {
56 e.printStackTrace();
57 }
58 return obj;
59 }
60 }
https://dzone.com/articles/5-different-ways-to-create-objects-in-java-with-ex 4/7
4/28/2018 5 Different Ways to Create Objects in Java - DZone Java
In the below Java program we are going to create Employee objects in all 5 ways. You can also find the
source code at GitHub.
3
4 // By using new keyword
6 emp1.setName("Naresh");
7
8 System.out.println(emp1 + ", hashcode : " + emp1.hashCode());
9
10 ×
11 // By using Class The Guide
class's to Java:
newInstance() method Development and Evolution
The Best Class.forName("org.programming.mitra.exercises.Employee")
Employee emp2 = (Employee) GoF Design Patterns for Microservices: Strategy, Façade & More
12 Benefits of Using the Future API in Kotlin
13 .newInstance();
Multi-Release JAR Files, Jigsaw Capabilities, and the jlink Tool in Java 9
14
15 // Or we can simply do this
19
20 System.out.println(emp2 + ", hashcode : " + emp2.hashCode());
21
22
23 // By using Constructor class's newInstance() method
26 emp3.setName("Yogesh");
27
28 System.out.println(emp3 + ", hashcode : " + emp3.hashCode());
29
30 // By using clone() method
32 emp4.setName("Atul");
33
34 System.out.println(emp4 + ", hashcode : " + emp4.hashCode());
35
36
37 // By using Deserialization
38
39 // Serialization
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.obj"));
https://dzone.com/articles/5-different-ways-to-create-objects-in-java-with-ex 5/7
4/28/2018 5 Different Ways to Create Objects in Java - DZone Java
ObjectOutputSt ea out e ObjectOutputSt ea ( e eOutputSt ea ( data.obj ));
40
41
42 out.writeObject(emp4);
43 out.close();
44
45 //Deserialization
48 in.close();
49
50 emp5.setName("Akash");
52
53 }
54 }
Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for
operational efficiency, meaningful analytics and good long-term customer relationships. But, when
dealing with multiple sources of data, data quality becomes complex, so you need to know when you
should build a custom data quality tools effort over canned solutions. Download our whitepaper for more
insights into a hybrid approach.
https://dzone.com/articles/5-different-ways-to-create-objects-in-java-with-ex 6/7
4/28/2018 5 Different Ways to Create Objects in Java - DZone Java
Published at DZone with permission of Naresh Joshi , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
https://dzone.com/articles/5-different-ways-to-create-objects-in-java-with-ex 7/7