Several ways to create objects in Java

Source: Internet
Author: User
Tags instance method shallow copy static class thread class

In a Java program, an object can be created explicitly or implicitly.
Here are four ways to explicitly create objects:
To create an object with the new statement
A newinstance () instance method that invokes the Java.lang.Class or Java.lang.reflect.Constructor class by means of reflection
Invoke the Clone () method of the object
By means of serialization, the ReadObject () method of the Java.io.ObjectInputStream object is invoked.

Example

Package dgut.ke.javatest;

public class Customer implements cloneable {

private String name;
private int age;

Public Customer () {
This ("Unknown", 0);
SYSTEM.OUT.PRINTLN ("Call default constructor");
}

Public Customer (String Name,int age) {
THIS.name = name;
This.age = age;
System.out.println ("Call second constructor");
}

Public Object Clone () throws Clonenotsupportedexception {
return Super.clone ();
}

public boolean equals (Object o) {
if (this = O)
return true;
if (! (o instanceof Customer))
return false;
Final Customer other = (customer) O;
if (This.name.equals (other.name) && this.age = = other.age)
return true;
Else
return false;
}

Public String toString () {
return "Customer.name =" +name+ "customer.age =" +age;
}
/**
* @param args
*/
public static void Main (string[] args) throws exception{
Using reflection to create a customer object
Class objectclass = Class.forName ("Dgut.ke.javatest.Customer");
Customer C1 = (customer) objectclass.newinstance ();
SYSTEM.OUT.PRINTLN ("C1-->" + C1);

Create a customer object with new
Customer C2 = new Customer ("Tom", 20);
System.out.println ("C2-->" + C2);

To create a customer object by means of cloning
Customer C3 = (customer) c2.clone ();
System.out.println ("C3-->" + C3);
System.out.println ("C2 = = C3" + (C2==C3));
System.out.println ("C2.equals (C3)" + C2.equals (C3));
}

}

Class class Forname method public static class<?> forname (String className)
Throws ClassNotFoundException
Returns the class object associated with the class or interface with the given string name. Calling this method is equivalent to:
Class.forName (ClassName, True, Currentloader)

Where Currentloader represents the definition class loader for this class.
For example, the following code fragment returns the Run-time class descriptor for the Java.lang.Thread class.

Class t = class.forname ("Java.lang.Thread")

Calling forname ("x") will cause the class named X to be initialized.

Parameters:
ClassName-The fully qualified name of the desired class.
Return:
Class object with the specified name.
Thrown:
Linkageerror-If the link fails
Exceptionininitializererror-If the initialization that this method fires fails
ClassNotFoundException-If the class is not found
The Clone () method of the object class

Protected Object Clone ()
Throws Clonenotsupportedexception
Creates and returns a copy of this object. The exact meaning of "replica" may depend on the class of the object. In general, for any object x, if an expression:
X.clone ()!= x
is correct, then an expression:
X.clone (). GetClass () = X.getclass ()
will be true, but these are not absolute conditions. In general, it is:
X.clone (). Equals (x)
will be true, but this is not an absolute condition.
By convention, the returned object should be obtained by invoking Super.clone. If a class and all its superclass (except Object) comply with this Convention, X.clone (). GetClass () = = X.getclass ().

By convention, the object returned by this method should be independent of the object (the object being cloned). To obtain this independence, it is necessary to modify one or more fields of the object before Super.clone returns the object. This usually means that you want to copy all the mutable objects that contain the internal "deep structure" of the object being cloned, and replace the reference to those objects with a reference to the replica. If a class contains only basic fields or references to immutable objects, you typically do not need to modify the fields in the objects returned by Super.clone.

The Clone method of the Object class performs a specific cloning operation. First, if the class of this object does not implement an interface cloneable, the clonenotsupportedexception is thrown. Note: All arrays are considered to implement Interface cloneable. Otherwise, this method creates a new instance of the class of this object and initializes all the fields of the object strictly using the contents of the corresponding field of the object, as is done by the assignment; the contents of these fields are not cloned by themselves. Therefore, this method performs a "shallow copy" of the object, rather than a "deep copy" operation.

The object class itself does not implement interface cloneable, so invoking the Clone method on an object that is class object causes the exception to be thrown at run time.

Returns:
A clone of this instance.
Thrown:
Clonenotsupportedexception-If the object's class does not support the Cloneable interface, the subclass of the override Clone method also throws this exception to indicate that an instance cannot be cloned.
See also:
cloneable

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.