In-depth study of the java. lang. Object Class

Source: Internet
Author: User

In-depth study of the java. lang. Object Class

Java class libraries are growing and contain countless classes and interfaces. But there are some very important classes and interfaces, which are the core part of the Java class library. Common include String, Object, Class, Collection, ClassLoader, System, Runtime..., Master Class is the basis of flexible Java language. These classes are generally well understood and used, and need to be thoroughly studied and practiced before they can be mastered.

I. Overview:
The Object class is the ancestor of all Java classes. Each class uses an Object as a superclass. All objects (including arrays) implement this class method.
If the superclass is not explicitly given, Java automatically uses the Object as the superclass of the class to be defined.
You can use a variable of the Object type to point to any type of Object.
The Object class has a default constructor pubilc Object (). When constructing a subclass instance, this default constructor is called first.
The variables of the Object class can only be used as the holders of various values. To perform any special operations on them, you need to know their original types and perform type conversion. For example:
Object obj = new MyObject ();
MyObject x = (MyObject) obj;

Ii. API Preview
Object ()
Default constructor
Clone ()
Create and return a copy of this object.
Equals (Object obj)
Indicates whether another object is "equal" to this object ".
Finalize ()
When the Garbage Collector determines that there is no more reference to this object, the object's garbage collector calls this method.
GetClass ()
Returns the runtime class of an object.
HashCode ()
Returns the hash value of the object.
Notify ()
Wake up a single thread waiting on this object monitor.
Policyall ()
Wake up all threads waiting on this object monitor.
ToString ()
Returns the string representation of the object.
Wait ()
This causes the current thread to wait until other threads call the notify () method or the notifyAll () method of this object.
Wait (long timeout)
This causes the current thread to wait until other threads call the notify () method or the yyall () method of this object, or exceed the specified time.
Wait (long timeout, int nanos)
This causes the current thread to wait until other threads call the notify () method or yyall () method of this object, or other threads interrupt the current thread, or the thread has exceeded the actual time.

Iii. Method instructions
1. equals () method: used to test whether an object is equal to another object. Its implementation in the Object class is to determine whether two objects point to the same memory area. This is not a big test, because even if the content of the object is the same, the memory area is different. If you want to test whether the objects are equal, you need to override this method for more meaningful comparison. For example
Class Employee {
... // This example is from volume 1 of java core technology.
Public boolean equals (Object otherObj ){
// Quickly test whether the object is the same
If (this = otherObj) return true;
// If the explicit parameter is null, false must be returned.
If (otherObj = null) reutrn false;
// It cannot be equal if the class does not match
If (getClass ()! = OtherObj. getClass () return false;

// Now we know that otherObj is a non-empty Employee object.
Employee other = (Employee) otherObj;

// Test whether all fields are equal
Return name. equals (other. name)
& Salary = other. salary
& HireDay. equals (other. hireDay );
}
}
Java language specifications require the equals method to have the following features:
Self-inverse: returns true for any non-null reference value x, x. equals (x.
Symmetry: For any non-null reference values x and y, x. equals (y) returns true only when y. equals (x) returns true.
Passed: For any non-null reference values x, y, and z, if x. equals (y) returns true, and y. equals (z) returns true, then x. equals (z) should return true.
Consistency: For any non-null reference values x and y, call x multiple times. equals (y) always returns true or false, provided that the information used in the equals comparison on the object is not modified.
Returns false for any non-null reference value x, x. equals (null.

The above example shows the standard implementation of the Java standard equals method. We recommend that you use the above example to implement the equals method of the class.

2. toString (): returns the string representation of the object. The toString () method in the Object class prints the class name and the memory location of the Object. Almost every class will overwrite this method to print the representation of the current state of the object. Most (not all) toString () methods follow the following format: class name [field name = value, field name = value...], of course, subclass should define its own toString () method. For example:

Public String toString (){
Reurn "Employee [name =" + name + ", salary =" + salary + ", hireDay =" + hireDay + "]";
}
The toString () method is a very important debugging tool. Many classes in the standard class library define the toString () method, so that programmers can obtain useful debugging information.


3. clone (): Creates and returns a copy of the object. The exact meaning of a copy may depend on the class of the object. This is intended for any object x,

Expression: x. clone ()! = X is true, and the expression x. clone (). getClass () = x. getClass () is also true, but these are not required.

Generally, x. clone (). equals (x) is true, but this is not a requirement that must be met.

4. Wake y (): Wake up a single thread waiting on this object monitor. If all threads are waiting on this object, the system will wake up one of the threads. The choice is arbitrary and occurs when a decision is made on the implementation. The thread waits on the object's monitor by calling one of the wait methods.
The wake-up thread can continue to be executed until the current thread abandons the lock on this object. The wake-up thread will compete with all other threads that actively Synchronize on the object in the conventional way; for example, the wake-up thread has no reliable privilege or disadvantage in serving as the next thread to lock this object.

This method should be called only by the thread that is the owner of this object monitor. One of the following three methods allows a thread to become the owner of the object monitor:

Execute the synchronization instance method of this object. By performing synchronization on this object synchronizedThe body of the statement. For ClassType object, you can execute the static synchronization method of this class.

Only one thread can own the monitor of the object at a time.


5. yyall (): Wake up all threads waiting on this object monitor. The thread calls one of waitMethod, waiting on the object's monitor.

The wake-up thread can continue to be executed until the current thread abandons the lock on this object. The wake-up thread will compete with all other threads that actively Synchronize on the object in the conventional way; for example, the wake-up thread has no reliable privilege or disadvantage in serving as the next thread to lock this object.


6. wait (long timeout): The current thread waits until other threads call the notify () method or notifyAll () method of this object or exceed the specified time.
The current thread must have this object monitor.
This method causes the current thread (T) to place itself in the waiting set of the object, and then discard all the synchronization requirements on the object. For the purpose of thread scheduling, thread T is disabled and in sleep state before one of the following four conditions occurs:

Another thread calls the notify method of this object, and thread T is chosen as the wake-up thread. Another thread calls the yyall method of this object. Other threads interrupt thread T. The specified actual time has been reached. However, if the timeout value is zero, the actual time is not considered. The thread will wait until the notification is received. Then, thread T is deleted from the object's waiting set and thread scheduling is re-executed. Then, the thread competes with other threads in a conventional manner to obtain the right to synchronize on the object. Once the thread obtains control over the object, all the synchronous declarations on the object will be restored to the previous state, which is the case when the wait method is called. Then, the thread T is returned from the wait method call. Therefore, the synchronization status of the object and thread T is the same as that of the wait method. The thread can also wake up a so-called spurous wakeup without being notified, interrupted, or timed out ). Although this rarely happens in practice, the application must use the following methods to prevent it from happening, that is, to test the conditions that should cause the thread to be reminded. If this condition is not met, then wait. In other words, the wait should always occur in the loop, as shown in the following example:
Synchronized (obj ){
While ( )
Obj. wait (timeout );
... // Perform action appropriate to condition
}


7. wait (long timeout, int nanos): Call the notify () method or notifyAll () method of this object in another thread, or interrupt the current thread in another thread, or the current thread waits until the actual time is exceeded.

This method is similar to the wait method of a parameter, but it allows better control of the amount of time waiting for notification before giving up. The actual time measured in milliseconds can be calculated using the following formula:
1000000 * timeout + nanos in all other aspects, the operations executed by this method are the same as those of the wait (long) method with a parameter. In particular, wait (0, 0) is the same as wait (0.

The current thread must have this object monitor. This thread releases ownership of this monitor and waits for one of the following two conditions to occur:

Other threads notify the waiting thread on the monitor of this object to wake up by calling the notify method or the notifyAll method. The time-out period specified for the sum of the timeout millisecond value and the nanos millisecond parameter value is used up. Then, the thread will not continue execution until it obtains ownership of the monitor again.
For a parameter version, it is possible to implement interruption and false wakeup, and this method should always be used in the Loop:
Synchronized (obj ){
While ( )
Obj. wait (timeout, nanos );
... // Perform action appropriate to condition
}

8. wait (): The current thread waits until other threads call the notify () method or notifyAll () method of this object. In other words, the behavior of this method is as if it only executes the wait (0) Call.


The current thread must have this object monitor. This thread releases ownership of this monitor and waits until other threads wake up on the monitor of this object by calling the notify method or the notifyAll method. Then the thread will not continue execution until it obtains ownership of the monitor again.


For a parameter version, interruption and false wakeup are possible, and this method should always be used in a loop:
Synchronized (obj ){
While ( )
Obj. wait ();
... // Perform action appropriate to condition
}


9. finalize (): When the Garbage Collector determines that there are no more references to this object, the object's garbage collector calls this method. Subclass override the finalize method to configure system resources or execute other cleanup operations.
The general protocol of finalize is that this method is called when the JavaTM virtual machine has determined that any thread that has not been terminated cannot access this object in any way, unless an operation is performed for the end operation of another object or class to be terminated. The finalize method can take any action, including re-enabling this object to be available to other threads; however, the main purpose of finalize is to clear the object before it can be unundone. For example, the finalize method of the input/output connection object can execute an explicit I/O transaction to interrupt the connection before the object is permanently discarded.


The finalize method of the Object class performs non-special operations; it only performs some common responses. This definition can be rewritten as a subclass of an Object.


The Java programming language does not guarantee which thread will call the finalize method of a given object. However, when you call finalize, the thread that calls finalize will not hold any visible synchronization locks. If the finalize method throws an uncaptured exception, the exception is ignored and the end operation of the object is terminated.


After the finalize method of an object is enabled, no further operations will be performed until the Java Virtual Machine confirms again that no threads have been terminated and cannot access this object in any way, these include the possible operations performed by other objects or classes to be terminated. When this operation is performed, the objects may be discarded.


For any given object, the Java Virtual Machine can only call the finalize method once.


Any exception thrown by the finalize method will stop the end operation of this object, but you can ignore it by other methods.

Related Article

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.