[Java] re-compile the method (zt) in the object class)

Source: Internet
Author: User
The object class is the superclass of all classes. That is to say, every class in Java is extended by the object. therefore, every time you create an object, it will have all the methods in the object class. let's take a look at java. lang. what are the main methods in object:
Public class object {
// Public Constructor
Public object ();
// Public instance method
Public Boolean equals (Object OBJ );
Public native int hashcode ();
Public final native class getclass ();
Public String tostring ();
Public final native void Policy ();
Public final native void policyall ();
Public final void wait () throws interruptedexception;
Public final native void wait (long timeout) throws interruptedexception;
Public final void wait (long timeout, int Nanos) throws interruptedexception;
// Instance protection method
Protected native object clone ();
Protected void finalize () throws throwable ;}
The equals method tests whether two objects are equal. The method clone is used to copy objects. The method getclass returns the class objects related to the current object, including notify, policyall, wait is used to synchronize threads for a given object.
However, the object class only provides some basic methods. We often need to cover these methods when writing our own classes. On the one hand, we need to enhance functions, and on the other hand, we want to adapt to the current situation. this leads to the topic of this article --
How to compile your own equals Method
First, we need to clarify the question: how does the equals method in the object class determine whether two objects are equal? Let's take a look at its source code:
Public Boolean equals (Object OBJ)
{
Return (this = OBJ );
}

It is easy to see that it only determines whether the references of two objects are equal, which in many cases does not have much practical significance. for example, we need to compare whether two strings are equal. This method is overwritten in the string class. the standard Java class library has over 150 equals methods. however, the Java language specification requires the equals method to have the following properties:
Inversion: returns true for any non-null reference X, X. Equals (X.
Symmetry: For any non-null references to X and Y, if and only if y. Equals (x) returns true, X. Equals (y) returns true.
Passed: For any reference of X, Y, and Z, if X. equals (y) returns true and Y. equals (z) also returns true, then X. equals (z) should return true.
Consistency: If the objects referenced by X and Y are not changed, repeated calls of X. Equals (y) should return the same result.
For any non-null reference X, X. Equals (null) should return false.
These five rules show good logic. If you want to write your own equals method, you must satisfy them. How can these rules be implemented?
Assume that the parameter passed in by the current equals method is named otherobject,
Test whether this is equal to otherobject.
Test whether otherobject is null. If yes, false must be returned.
Test whether otherobject belongs to the same class through this. This is to satisfy the rule 2.
Forcibly convert otherobject to another variable (called other): classname Other = (classname) otherobject. then compare all fields. use = to compare basic type fields, and use the equals method to compare object fields. true is returned if all fields match. Otherwise, false is returned.
The following is a simple example:
Class testequal {
Int number;
String S;
Public Boolean equals (Object otherobject ){
// First, check whether the two object references are equal.
If (this = otherobject)
Return true;
// This is to satisfy Rule 5
If (otherobject = NULL)
Return false;
// If two objects belong to different types, they cannot be equal
If (getclass ()! = Otherobject. getclass ())
Return false;
Testequal Other = (testequal) otherobject;
// Compare all fields
Return S. Equals (otherobject. s) & number = otherobject. number;
}
}
Although this example is simple, it clearly reflects the points mentioned above.
Note that in the subclass, you must first call the super-class equals method. If this test fails, the two objects cannot be equal. That is:
If (! Super. Equals (otherobject) return false;

I believe that you have a certain understanding of writing your own equals method. It is not difficult to write a program as long as you pay more attention to it.
Let's take a look at the second topic of this article:

How to compile your own clone method
Similar to the equals method, let's first discuss how the object clone method works. however, before that, we have a question: all the classes that use the clone method, whether inheriting objects. clone () or overwrite it, you must implement an interface named cloneable. if you open the Java class library, you will find that there is nothing in this interface. It only indicates that a class has the ability to be cloned.
Use an example to study the replication Effect of object. Clone:
Public class testclone1 implements cloneable {
Int count;
Testclone1 next;
Public testclone1 (INT count ){
This. Count = count;
If (count> 0)
Next = new testclone1 (count-1 );
}
Void add (){
Count ++;
If (next! = NULL)
Next. Count ++;
}
Public String tostring (){
String S = string. valueof (count) + "";
If (next! = NULL)
S + = next. tostring ();
Return S;
}
Public object clone (){
Object o = NULL;
// If cloneable is not implemented, a clonenotsupported exception will be thrown.
Try {
O = super. Clone ();
}
Catch (clonenotsupportedexception e ){
System. Err. println ("cannot clone ");
}
Return O;
}
Public static void main (string [] ARGs ){
Testclone1 T = new testclone1 (1 );
System. Out. println ("t =" + t );
Testclone1 T1 = (testclone1) T. Clone ();
System. Out. println ("T1 =" + T1 );
T. Add ();
System. Out. println ("after addedt T =" + T + "T1 =" + T1)
}
}

In this example, the creation of T is equivalent to two connected testclone1 instances. After the t add method is called, unexpected results are displayed:
T = 1 0
T1 = 1 0
After added
T = 2 1
T1 = 1 1
T1. actually object. the clone () mechanism involves the "bitwise" principle, that is, one-bit replication. for an object defined in an object, it simply copies the reference of this object. this is also the so-called shallow copy. It is difficult to execute deep copy.
You only need to add t1.next = (testclone1) T. Clone () to testclone1 T1 = (testclone1) T. Next. Clone (); To get:
T = 1 0
T1 = 1 0
After added
T = 2 1
T1 = 1 0
This is the correct result.
Next we will introduce how to control the clone capability. as you can see before, clone () is protected. You must overwrite and implement the cloneable interface and handle the necessary exceptions before using it. in this way, when designing your own class, you have the following styles to control the clone capability:
Ignore clone (), that is, your class does not involve any content related to clone (). If someone wants to implement the clone function, you must write a subclass and fulfill the requirements described above. this is suitable for object. clone () can be used to copy all fields in your class.
Clone () is supported. You implement the cloneable interface in your class, overwrite the clone method, and capture the corresponding exceptions.
Conditional support for clone (). this situation is special, that is, your class stores references to objects that may not be copied (here they do not implement cloneable ). at this time, you just copy all these objects in clone (). If an exception occurs, throw all these exceptions to the person who uses your class. for example, if you are writing a class similar to arraylist, you do not know what objects will be stored in your arraylist, so you don't know if they can be copied.
Cloneable interface is not implemented, but the clone method is overwritten as protected. in this way, although your class cannot be copied, you provide the correct clone method. In this way, if someone wants to copy your class, write a subclass to implement the cloneable interface.
Do not implement the cloneable interface and overwrite the clone method to directly throw an exception to prevent your class from being copied. however, this is not a fundamental solution. It can only deal with those that call your clone method directly or call Super in the subclass. clone.
Use final to modify your class to prevent your class from being copied. if your superclass overwrite the clone method, overwrite the clone method again and throw an exception. this is also the most thorough approach.
We hope that this article will give you a general understanding of the object class and write your own equals and clone methods to meet different needs.

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.