Skip to main content

5 Different ways to create objects in Java with Example

While being a Java developer we usually create lots of objects daily, but we always use the new or dependency management systems e.g. Spring to create these objects. However, there are more ways to create objects which we are going to study in this article.

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.

5-different-ways-of-object-creation-in-Java-with-example-and-explanation

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.

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 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 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 clone method does not invoke any constructor.

To use 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 ExampleJava Cloning - Copy Constructor Versus CloningJava 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 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).

Example

Let’s consider an Employee class for which we are going to create the objects

class 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 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

Comments

  1. how to create an object with a name given by the user in java

    ReplyDelete
    Replies
    1. Basically it is not possible in Java, However you can achieve it using maps or other kinds of caching, you read more on stackoverflow http://stackoverflow.com/questions/19590265/how-to-define-a-java-object-name-with-a-variable

      Delete
  2. Thank you! With the help of this site I enhance my vender app

    ReplyDelete

Post a Comment

Popular posts from this blog

Why Single Java Source File Can Not Have More Than One public class

According to Java standards and common practices we should declare every class in its own source file. And even if we declare multiple classes in the single source file (.java) still each class will have its own class file after compilation. But the fact is that we can declare more than one class in a single source file with below constraints, Each source file should contain only one public class and the name of that public class should be similar to the name of the source file. If you are declaring the main method in your source file then main should lie in that public class If there is no public class in the source file then main method can lie in any class and we can give any name to the source file. If you are not following 1st constraint then you will receive a compilation error saying “ The public type A must be defined in its own file ”.  While if you are not following the second constraint you will receive an error “ Error: Could not find or load main class User ” after ...

Java Cloning - Copy Constructor versus Cloning

In my previous article Java Cloning and Types of Cloning (Shallow and Deep) in Details with Example , I have discussed Java Cloning in details and answered questions about how we can use cloning to copy objects in Java, what are two different types of cloning (Shallow & Deep) and how we can implement both of them, if you haven’t read it please go ahead. In order to implement cloning, we need configure our classes to follow below steps Implement Cloneable interface in our class or its superclass or interface, Define clone() method which should handle CloneNotSupportedException (either throw or log), And in most cases from our clone() method we call the clone() method of the superclass. And super.clone() will call its super.clone() and chain will continue until call will reach to clone() method of the Object class which will create a field by field mem copy of our object and return it back. Like everything Cloning also comes with its advantages and disadvantages. However, Java c...

Spring Data JPA Auditing: Saving CreatedBy, CreatedDate, LastModifiedBy, LastModifiedDate automatically

In any business application auditing simply means tracking and logging every change we do in the persisted records which simply means tracking every insert, update and delete operation and storing it. Auditing helps us in maintaining history records which can later help us in tracking user activities. If implemented properly auditing can also provide us similar functionality like version control systems. I have seen projects storing these things manually and doing so become very complex because you will need to write it completely by your own which will definitely require lots of code and lots of code means less maintainability and less focus on writing business logic. But why should someone need to go to this path when both JPA and Hibernate provides Automatic Auditing which we can be easily configured in your project. And here in this article, I will discuss how we can configure JPA to persist CreatedBy, CreatedDate, LastModifiedBy, LastModifiedDate columns automatically for any ...