5 ways to create objects in Java

Source: Internet
Author: User

Use the New keyword }→ called the constructor
Using the class Newinstance method }→ called the constructor
Using the Newinstance method of the constructor class }→ called the constructor
Using the Clone method }→ no constructor is called
Using deserialization }→ no constructor is called

If you run the program at the end, you will find that method 4,5 creates the object with the constructor, and the method does not call the constructor.

1. Use the New keyword

This is the most common and simplest way to create objects. In this way, we can call any constructor (with no arguments and with parameters).

Employee EMP1 = new Employee (); 0:new           #19          //class Org/programming/mitra/exercises/employee3:dup4: Invokespecial #21          //Method org/programming/mitra/exercises/employee. ":() V
2. Using the class Newinstance method

We can also use the class class's Newinstance method to create an object. This newinstance method calls the parameterless constructor to create the object.

We can create an object by calling the Newinstance method 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 the Newinstance method of the constructor class

Like the Newinstance method of class, there is also a newinstance method in the Java.lang.reflect.Constructor class that can create objects. We can call the parameterized and private constructors through this newinstance method.

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;

These two newinstance methods are what we call reflection. In fact, class's Newinstance method internally calls constructor's Newinstance method. This is also why many frameworks, such as spring, Hibernate, struts, etc. use the latter. To understand the differences between the two newinstance methods, see this article creating objects through Reflection in Java with Example.

4. Using the Clone method

Whenever we invoke the Clone method of an object, the JVM creates a new object that copies the contents of the preceding object in its entirety. Creating an object with the Clone method does not call any constructors.

To use the Clone method, we need to implement the Cloneable interface first and implement its definition of the Clone method.

Employee Emp4 = (employee) emp3.clone () 162:invokevirtual #87  //Method org/programming/mitra/exercises/ Employee.clone () Ljava/lang/object;
5. Using deserialization

When we serialize and deserialize an object, the JVM creates a separate object for us. When deserializing, the JVM creates an object and does not call any constructors.
In order to deserialize an object, we need to have our class implement the Serializable interface

ObjectInputStream in = new ObjectInputStream (New FileInputStream ("Data.obj")); Employee EMP5 = (employee) in.readobject () 261:invokevirtual  #118   //Method java/io/ Objectinputstream.readobject: () Ljava/lang/object;

We can see from the above bytecode fragment that in addition to the 1th method, the other 4 methods are all transformed into invokevirtual (the direct method of creating the object), the first method is converted to two calls, and the new and Invokespecial (constructor call).

Example

Let's take a look at creating an object for the following employee class:

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 following Java program, we will create the employee object in 5 ways. You can find this code from 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.exer Cises.        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.getCo        Nstructor ();        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 fileoutputs        Tream ("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 ()); }}

The program will output:

Employee Constructor called ... Employee [Name=naresh], hashcode: -1968815046employee Constructor called ... Employee [Name=rishi], Hashcode:78970652employee Constructor called ... Employee [Name=yogesh], hashcode: -1641292792employee [Name=atul], Hashcode:2051657employee [Name=akash], hashcode:63 313419

5 ways to create objects in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.