Methods for creating objects in Java

Source: Internet
Author: User

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

2. Using the Reflection method, call the Java.lang.Class or Java.lang.reflect.Constructor class newinstance () instance methods.

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

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

I. Creating an object with the new statement

Java code
    1. User user = new user ()



Two. Use of reflective means
(1) Call Java.lang.Class.newInstance ()

Java code
    1. Class.forName (classname). newinstance ()
    2. Wife Wife = (Wife) class.forname ("Com.java.clone.Wife"). newinstance ();


(2) Call the newinstance () of the Java.lang.reflect.Constructor class

Java code
    1. Constructor Constructor = Wife.class. Getdeclaredconstructor (Int.class,string.class);
    2. Wife Wife = (Wife) constructor.newinstance (1, "Nihao");


Three. Calling the object's clone () method

Java code
      1. Wife Wife = new Wife (1, "Wang");
      2. Wife wife2 = null;
      3. Wife2 = (Wife) wife.clone ();//Use the Clone () method to produce a new object

Methods for creating 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.