5 ways to create objects in Java

Source: Internet
Author: User

As Java developers, we create a lot of objects every day, but we often use dependency management systems like spring to create objects. However, there are many ways to create objects, which we will learn from this article.

There are 5 ways to create objects in Java, given their examples and their bytecode.

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).

New Employee (); 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"= 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  = 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

New ObjectInputStream (new FileInputStream ("data.obj"= (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:

classEmployeeImplementscloneable, Serializable {Private Static Final LongSerialversionuid = 1L; PrivateString name;  PublicEmployee () {System.out.println ("Employee Constructor called ..."); }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; } @Override Public inthashcode () {Final intPrime = 31; intresult = 1; Result= Prime * result + ((name = =NULL) ? 0: Name.hashcode ()); returnresult; } @Override Public Booleanequals (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 PublicString toString () {return"Employee [name=" + name + "]"; } @Override PublicObject Clone () {Object obj=NULL; Try{obj=Super. Clone (); } Catch(clonenotsupportedexception e) {e.printstacktrace (); }        returnobj; }}

In the following Java program, we will create the employee object in 5 ways. You can find this code from GitHub.

 Public classobjectcreation { Public Static voidMain (String ... args)throwsException {//by using new keywordEmployee EMP1 =NewEmployee (); Emp1.setname ("Naresh"); System.out.println (Emp1+ ", Hashcode:" +Emp1.hashcode ()); //by using Class class ' s Newinstance () methodEmployee 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 () methodConstructor<employee> Constructor = Employee.class. GetConstructor (); Employee Emp3=constructor.newinstance (); Emp3.setname ("Yogesh"); System.out.println (Emp3+ ", Hashcode:" +Emp3.hashcode ()); //by using Clone () methodEmployee Emp4 =(Employee) Emp3.clone (); Emp4.setname ("Atul"); System.out.println (Emp4+ ", Hashcode:" +Emp4.hashcode ()); //by using deserialization//SerializationObjectOutputStream out =NewObjectOutputStream (NewFileOutputStream ("Data.obj"));        Out.writeobject (Emp4);        Out.close (); //deserializationObjectInputStream in =NewObjectInputStream (NewFileInputStream ("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

Related Article

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.