Chapter 3 of advanced Java technology-Explanation of the Object class in Java

Source: Internet
Author: User

Chapter 3 of advanced Java technology-Explanation of the Object class of Java's "", explanation of the object class
Preface

Preface click here to view:
Http://blog.csdn.net/wang7807564/article/details/79113195

Object Class

Java is a single inheritance, so the Obeject class is the parent class of all classes. The source code defined in JDK1.8 is:

public class Object {    private static native void registerNatives();    static {        registerNatives();    }    public final native Class<?> getClass();    public native int hashCode();    public boolean equals(Object obj) {        return (this == obj);    }    protected native Object clone() throws CloneNotSupportedException;    public String toString() {        return getClass().getName() + "@" + Integer.toHexString(hashCode());    }    public final native void notify();    public final native void notifyAll();    public final native void wait(long timeout) throws InterruptedException;    public final void wait(long timeout, int nanos) throws InterruptedException {        if (timeout < 0) {            throw new IllegalArgumentException("timeout value is negative");        }        if (nanos < 0 || nanos > 999999) {            throw new IllegalArgumentException("nanosecond timeout value out of range");        }        if (nanos > 0) {            timeout++;        }        wait(timeout);    }    public final void wait() throws InterruptedException {        wait(0);    }    protected void finalize() throws Throwable { }}

The content related to the equals () and hashCode () Methods of the Object class has been mentioned earlier, including wait () and Policy () and so on.

The clone () method of the Object class and deep and shallow copy:
The clone () method of the Object class is to copy an existing Object into a new Object. The new object and the original Copied object occupy two different memory spaces. The relationship between the two is not a reference relationship.

However, the clone () method of the Object class is implemented by defaultShortest copyReplication mode.
In the process of object copying, the eight basic data types are copied by value, by default, the object is copied according to the reference, that is, the object in the past is a reference, not a specific value stored in the memory.
Here we need to note that although the String type is a class, the clone () method also copies the data by value, which is the same as the eight basic data types, similar to the String class, the deep copy class can also be automatically performed, as well as the packaging class of the basic type mentioned later.
For example, the following example defines a class named Test:

class Test implements Cloneable{    Test_val test_val = null;    Test(Test_val t){        test_val =  t;    }    @Override    protected Object clone() throws CloneNotSupportedException {        return super.clone();    }}

This class defines an internal attribute, which is of the Test_val type. This is a class, which is defined:

class Test_val{    int i = 0;    Test_val(int i){        this.i = i;    }}

Write the following test code in the main () method:

public class Main {    public static void main(String []argv) throws Exception{        Test test1 = new Test(new Test_val(100));        Test test2 = (Test) test1.clone();        System.out.println(test1.test_val == test2.test_val);        test1.test_val.i = 1;        System.out.println(test1.test_val.i);    }}

The output result is:

True
1

That is, the copied test2 object is the same memory address as the test_val variable in test1 object. This attribute value in test1 is modified, and the value of this attribute in test2 object will also change.
It can be seen that this is not completely copied, so it is called a shallow copy. Correspondingly, if the internal attribute type of the object to be copied is the basic data type, it is copied by value. There will be no such object being modified, and the content of all objects will change, so it is a deep copy.
To realize deep copying of class types, We need to rewrite the clone () method based on our own business scenarios. When rewriting, note that it must implement the cloneable interface. Otherwise, an exception is reported. At the same time, because the clone () method in the Object parent class is proteced, to use the clone () method for a custom method, you need to write the code:

    @Override    protected Object clone() throws CloneNotSupportedException {        return super.clone();    }

The reference value is stored in the stack, and the specific object content is stored in the memory heap. The shallow copy only copies the reference stored in the stack, the specific content stored in the heap is not copied. The more complex the reference link is, the more clone () methods need to be rewritten,In actual development, it is very difficult to implement absolute deep copy.
Java's deep copy implements the Prototype Pattern in the design Pattern ).
The so-called prototype mode is to use a prototype instance to specify the type of the object to be created, and create a new object by copying the prototype. Therefore, the prototype mode is mainly used to copy objects, while implementing the cloneable interface and rewriting the clone () method process is the process of implementing the prototype mode.

Object finalize () method:

When the JVM garbage collector wants to recycle garbage objects, it must first call the finalize () method of this class. This process is called the finalization mechanism of Java. Generally, classes written in pure Java do not need to overwrite this function. However, if JNI is used to call the code written in C ++, you can rewrite this method to complete the further finishing of memory spam. For the collection of most Java resources, you do not need to rewrite this method. At the same time, because the calling of this method consumes a large amount of system resources, it is generally not recommended to rewrite this method.
In some cases, we also rewrite the finalize () method to complete specific functions, such as revoking non-Java resources. It is common to call Windows system resources, such as file handles and character fonts.
When rewriting this method, it should be noted that this method is also modified using protected, that is, to rewrite this method, you need to use the clone () rewrite method with the same method:

    @Overrideprotected void finalize() throws Throwable {    super.finalize();    //define your codes. }

However, in many cases, it is not recommended to rewrite this function, because in some cases, rewriting this function may not only increase efficiency, but also increase overhead, before rewriting, You need to weigh it.

View comments

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.