"Learning Notes" 5 methods for generating objects in Java

Source: Internet
Author: User
Tags instance method

Overview: This article describes the following Java five ways to create objects:

1. Create objects with the new statement, which is the most common way to create objects.

2. Using the class Newinstance method

3. Use reflection to invoke the newinstance () instance method of the Java.lang.reflect.Constructor class.

4. Call the object's clone () method.

5. Invoke the ReadObject () method of the Java.io.ObjectInputStream object using the deserialization means.

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

Second, using the class Newinstance method

  create an object using the class Newinstance method. This newinstance method calls the parameterless constructor to create the object .

Third, using the Newinstance method of 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.

The Newinstance method internally calls the constructor Newinstance method. This is also why many frameworks, such as spring, Hibernate, struts, etc. use the latter.

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

1  Public classCustomerImplementscloneable{2 PrivateString name; 3 Private intAge ; 4  PublicCustomer () {5    This("Unknown", 0); 6SYSTEM.OUT.PRINTLN ("Call default constructor"); 7 }  8  PublicCustomer (String name,intAge ) {  9    This. name=name; Ten    This. age=Age ;  OneSystem.out.println ("Call second constructor");  A }   -  PublicObject Clone ()throwsclonenotsupportedexception{ - return Super. Clone ();  the }   -  Public Booleanequals (Object o) { -   if( This==o)return true;  -   if(! (OinstanceofCustomer))return false;  +   FinalCustomer other=(Customer) o;  -   if( This. Name.equals (Other.name) && This. age==other.age) +      return true;  A   Else   at      return false;  - }   -  PublicString toString () { - return"Name=" +name+ ", age=" +Age ;  - }   -  Public Static voidMain (String args[])throwsexception{ in //using reflection to create a customer object -Class objclass=class.forname ("Customer");  toCustomer c1= (Customer) objclass.newinstance ();//invokes the default construction method of the Customer class +SYSTEM.OUT.PRINTLN ("C1:" +C1);//Print name=unknown,age=0 -     the //Create a Customer object with the new statement *Customer c2=NewCustomer ("Tom", 20);  $System.out.println ("C2:" +C2);//Print name=tom,age=20Panax Notoginseng     - //creating a Customer object using cloning theCustomer c3= (Customer) C2.clone ();//the construction method of the customer class is not called +System.out.println ("C2==C3:" + (C2==C3));//Print False ASystem.out.println ("C2.equals (C3):" +c2.equals (C3));//Print True theSystem.out.println ("C3:" +C3);//Print name=tom,age=20 + }   -}

V. The use of 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 EMP = (employee) in.readobject ();

Note: In addition to the 1th method, all 4 other methods are converted to invokevirtual (the direct method of creating the object), the first method is transformed into two calls, and new and Invokespecial (constructor calls).

In addition to the above 5 ways of explicitly creating objects, you can implicitly create objects in your program, including the following scenarios:

1. For each command-line argument in the Java command, the Java virtual machine creates the corresponding string object, organizes it into a string array, and passes the array as a parameter to the program entry main (String args[]) method.

2. The direct number of the string type in the program code corresponds to a String object, for example:

    1. String s1="Hello";
    2. String s2="Hello"; //s2 and S1 reference the same string object
    3. String s3=new String ("Hello");
    4. System.out.println (S1==S2); //Print True
    5. System.out.println (S1==S3); //Print false

After executing the above program, there are actually only two string objects in memory, one is the direct number, implicitly created by the Java Virtual machine, and one is explicitly created by the new statement.

3. The operation result of the string operator "+" is a new string object. For example:

    1. String s1="H";
    2. String s2="Ello";
    3. String s3=s1+s2; //S3 refers to a new string object
    4. System.out.println (s3=="Hello"); //Print false
    5. System.out.println (S3.equals ("Hello")); //Print True

4. When a Java virtual machine loads a class, it implicitly creates a class instance that describes the class.

Resources:

There are several ways to generate objects in Java, as follows:

 1, using the new operator, is the most common kind of     such as String S=new string ("abc"),   2, dynamic generation using reflection       Use the methods in Class,classloader,constructor to dynamically generate class instances      such as: Object O=class.forname (" Java.lang.String "). newinstance ();         object o= String.class.getClassLoader.loadClass ("Java.lang.String"). Newinstance ();       The    above requires that the target class have a public parameterless constructor      the following is dynamically generated using constructor     class User {       public User (String user,integer ID) {}    }     constructor c=user.class.getconstructor (New Class[]{string.class,integer.class});     user user= (User) c.newinstance (new object[]{"Zhang San", 123});  3, using clones to generate objects     For example, using an object that implements the Cloneable interface, call its clone () method to get a copy of the object    4, use deserialization to generate objects from the stream     Generating objects using Objectinptustream's ReadObject () method

Learning notes 5 ways to generate 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.