HubFirms

HubFirms : Blog -5 Different Ways to Create Objects in Java

5 Different Ways to Create Objects in Java

5 Different Ways to Create Objects in Java

Being Java engineers, we more often than not make heaps of items every day, except we generally use reliance the board frameworks for example Spring to make these articles. Be that as it may, there are more approaches to make objects, which we will consider in this article. 

There are five all out approaches to make questions in Java, which are clarified underneath with their models pursued by bytecode of the line which is making the item. 

In the event that you will execute program given at last, you will see technique 1, 2, 3 utilizes the constructor to make the item while 4, 5 doesn't call the constructor to make the article. [Top 50 Java Interview Questions and Answers]

1. Utilizing new watchwords 

It is the most widely recognized and standard approach to make an article and an extremely basic one too. By utilizing this strategy we can call whichever constructor we need to call (no-arg constructor just as parameterized).

Java for iOS? Gluon Client plugins support Java & JavaFX on iOS devices
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. Utilizing newInstance() strategy for class 

We can likewise utilize the newInstance() strategy for a class to make an item. This newInstance() technique calls the no-arg constructor to make the article. 

We can make an article by newInstance() in the accompanying 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. Utilizing newInstance() technique for Constructor class 

Like the newInstance() strategy for class, There is one newInstance() technique in the java.lang.reflect.Constructor class which we can use to make objects. We can likewise call parameterized constructor, and private constructor by utilizing this newInstance() strategy.

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;

Both newInstance() strategies are known as intelligent approaches to make objects. Actually newInstance() strategy for class inside utilizations newInstance() technique for Constructor class. That is the reason the later one is liked and furthermore utilized by various structures like Spring, Hibernate, Struts and so forth. To know the contrasts between both newInstance() strategies read Creating objects through Reflection in Java with Example. 

4. Utilizing clone() strategy: 

At whatever point we call clone() on any item, the JVM really makes another article for us and duplicates all substance of the past item into it. Making an item utilizing the clone technique does not summon any constructor. 

To utilize clone() technique on an item we have to actualize Cloneable and characterize the clone() strategy 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 far from being obviously true point in Java people group and it doubtlessly has its downsides however it is as yet the most mainstream and simple method for making a duplicate of any item until that article is full filling compulsory states of Java cloning. I have shrouded cloning in subtleties in a 3 article long Java Cloning Series which incorporates (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), feel free to peruse them in the event that you need to find out about cloning. 

Javalin 2.8.0 arrives with Micrometer support and important Misc fixes

5. Utilizing Deserialization: 

At whatever point we serialize and deserialize an item, the JVM makes a different article for us. In deserialization, the JVM doesn't utilize any constructor to make the item. 

To deserialize an item, we have to actualize a Serializable interface in our group.

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 should be obvious in the above bytecode bits, every one of the 4 techniques are called and get changed over to invokevirtual (object creation is straightforwardly dealt with by these strategies) aside from the first, which got changed over to two calls: one is new and other is invokespecial (call to the constructor). 

I have talked about serialization and deserialization in more subtleties in my article, Everything About Java Serialization Explained With Example, it would be ideal if you feel free to peruse it in the event that you need to find out about it.[Top 100 Java Interview Questions and Answers]

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 the below Java program, we are going to create Employee objects in all 5 ways.[Top 20 Java Interview Questions and Answers]

An Introduction to the Java Collections Framework

 

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
How to Create an Array List in Java

Author Biography.

Hub Firms
Hub Firms

HubFirms is one of the world’s largest online publications that delivers an international perspective on the latest news about Internet technology, business and culture.

Related Posts