Java source Learning-Detailed object class

Source: Internet
Author: User
Tags instance method modifiers

Java language Learning, the study of JDK source code is mastered basic grammar, the ability to upgrade a very important way.

This content mainly resolves the following content:

1) A simple summary of the methods in object;

2) The interpretation of each method, including the points of attention and development needs attention;

3) A brief description of the functions of these methods in object is related to those features in the Java language;

/*
  The object class is the root class of the Java class hierarchy, which is the parent class of all classes. All classes, including arrays, implement the methods in the object class.
  The permission modifier of the class is also important, see the permission modifier
*/
publicclass Object { }

/*
  Registernatives (), which is private to the object class, primarily registers the local method with the virtual machine
*/

Privatestaticnativevoid registernatives (); Static {registernatives ();}

/*
  Public: Indicates that the method is publicly owned, final decorated, representing the address references of the bytecode object that each class gets, where it is fixed in memory, native decorated, and implemented with virtual machines.
*/
 Public Final native Class<?> getclass ();

/*
Function: Returns the hash value of the current object
Purpose: To provide services for a hash table in Java
Precautions:
1) During the run of a Java application, this method is called multiple times by the same object, and the same integer should be returned.
2) for the same object, the first run of the program to get the Hashcode value and the second run of the program to get the Hashcode value can be different
3) If two objects are judged by the Equals (object) method as true, then both objects call their respective hashcode methods to return the same integer value
4) Two objects returned by the Equals method are false, so the return value of their respective hashcode methods can be the same (or different). However, as a programmer, you should be aware that the result of two objects returned by the Equals method should be the same as the result of the return value of the Hashcode method.
This will improve the performance of the hash table. This is why it is necessary to rewrite the Hashcode method when overriding the Equals method.
*/
publicnativeint hashcode ();

/*
  Function: Used to indicate whether this object and other objects are equal.
Characteristics:
1 Reflexivity An object should be equal to itself
2 symmetry for two non-null references, x, y; X.equals (y) results are consistent with y.equals (x)
3 transitivity for any of the non-null references x, y, z, x.equals, = = True X.equals (z) = = True, then Y.equals (z) = = True
4 consistency
5 Uniqueness for any non-null reference x,x.equals (NULL) = = = False

Precautions:
1 when the Equals method is not overridden, for any two non-null references x, y if x.equals (y) means that they point to the same address reference
2 when the Equals method is overridden, the Hashcode method needs to be rewritten to maintain a contract, and the result of the Equals method is consistent with the results of the Hashcode method
*/

Public Booleanequals (Object obj) {return( This==obj);}

/*
  Permission modifier: Protected, this is very important, the meaning is very simple only the class own object can call this method, ensure the security, maintain the order.
Exception : Clonenotsupportedexception, Object calls the Clone () method, which is required to implement the Cloneable interface (the object class does not implement this interface object obj = new Object (); Obj object does not have a clone () method), otherwise this exception is thrown at run time
Function : Creates and returns a copy of the current object. this copy and the original object are not always consistent, that is, this is a shallow copy (with a deep copy of the details will be described in detail in another article, and give a concrete implementation). The specific analysis is as follows:
1. For a non-empty object X.clone ()! = X,x and X.clone () have different memory addresses
2, X.clone (). GetClass () = = X.getclass () is True
3. The interface of the array type implements the Cloneable interface, and if the type of the array is loaded with the base data type (int,double,string, etc.), the method is used, and the value is present in the object of the new clone.
*/

Protectednativethrows clonenotsupportedexception;
/*
  Function: Returns a string representation of the current object.
GetClass (). GetName () Gets the current byte-code object and then gets the package name of the current object + class name
Return Result: The current object's package name + class name + "@" + 16-binary representation of the current object's Hashcode value

Recommendation: Override this method for all objects that need to describe the class information, because such a form is not conducive to the visual description of the object's information
*/

public String toString () { return getclass (). GetName () + "@" integer.tohexstring ( Hashcode ());}

 /* 
function: Wake up a single thread that is waiting for this object monitor
Note:
1) If there are multiple threads waiting for this object, then only one thread can be awakened, The thread being awakened is random.
2) to implement a thread waiting for an object monitor by calling the wait method
3) The wake-up thread can only execute if the current object's lock is discarded by the front path. But the awakened thread does not have the privilege or disadvantage to get the next lock on the object (random)

Span style= "font-size:14px" > method call:
1) This method can be called by the owner of this thread object monitor.
A thread has this object monitor in general there are three ways:
1 instance methods on the
2 method within a block of code (instance methods and static methods, an instance method can be any object, a static method is only a bytecode file object of the current class)
3 on a static method
*/
Public final native void notify (); Three ways to

Object monitor:
1  Public classObjectstudy {2 3     PrivateObject lock =NewObject ();4     5     /**6 * The body of the statement is synchronized on the current class object7      */8      Public synchronized voidTest () {9System.out.println ("Hello test1 ...");Ten     } One  A     /** - * Synchronize with any object, you can use this -      */ the      Public voidtest2 () { -System.out.println ("Hello World"); -         synchronized(lock) { -System.out.println ("Hello test2 ..."); +         } -     } +  A     /** at * Synchronous static method of class -      */ -      Public synchronized Static voidtest3 () { -System.out.println ("Hello test3 ..."); -     } -      Public Static voidtest4 () { in         synchronized(Newobjectstudy (). GetClass ()) { -System.out.println ("Hello test3 ..."); to         } +     } -}

/*
  Function: Wakes all monitors that are waiting on this object
Precautions:
1 Although all threads are awakened, only one thread can execute at the same time
Method invocation See Notify () method
*/
publicfinalnativevoid notifyall ();

/*
  Function: Causes the current thread to wait until another thread calls the Notify method or the Notifyall () method, or more than the specified time, which begins execution
*/
Public finalnativevoid Wait (longthrows Interruptedexception;

/*
  Features: Keeping threads in a wait state
Parameters:
Long timeout-The maximum time to wait, in milliseconds
int Nanos--additional time, improved accuracy, range of values at 0-999999
Abnormal:
A run-time exception is thrown when a parameter is unqualified
*/



Public Final voidWaitLongTimeoutintNanosthrowsinterruptedexception {if(Timeout < 0) {Throw NewIllegalArgumentException ("Timeout value is negative");}if(Nanos < 0 | | Nanos > 999999) {Throw NewIllegalArgumentException ("Nanosecond timeout value out of range");} TheTimeout to take a reasonable value
if (Nanos >= 500000 | | (Nanos! = 0 && Timeout = = 0)) {
Timeout+ +


}

/*
  
*/
public finalvoidthrows interruptedexception { Wait (0);}

/*
  Function: The garbage collector calls this method for garbage collection when the garbage collector considers that the reference to the object is not being referenced at any time.
Modifier: Protected the subclass can override this method to process system resources and perform other cleanup operations.
*/
protectedvoidthrows throwable {}

Summarize:

  Local method 7 :

private static native void Registernatives ()

Public final native class<?> GetClass ()

public native int Hashcode ()

Protected native Object clone ()

Public final void Notify ()

Public final native void Notifyall ()

Public final native void wait (long timeout)

non-native method 5 :

public boolean equals (Object obj)

Public String toString ()

Public final void Wait (Long timeout,int Nanos)

Public final void Wait ()

protected void Finalize ()

Static code block:

static {

Registernatives ();

}

  First, experience the charm of the permission modifier, private,public,protected, in addition to the package-level default modifier, the object class is fully contained; now briefly analyze:

1) private static native void Registernatives (), this method is only called by the object class itself, executed when the object class is loaded, mainly registering several local methods (which can be understood as mapping local methods to virtual machines)

2) Public final native class<?> GetClass (), note the final modifier before the method, indicating that this method is implemented by a virtual machine, and subclasses cannot override

3) public native int hashcode (), which is also a local method, but allows subclasses to override it

4) protected native Object clone (), the permission modifier for this method is protected, what about public?

A) The protected keyword is interpreted, under the same package, the object of the class can access to the protected decorated method, the subclass of the class can in any case access to the parent class protected decorated method

b) If a class does not override the Clone () method, only the object that created the class in the class can access the Clone () method, because the Clone () method of the object class is accessed at this time, and access to the Clone () method is accessed based on the relationship of the child parent class. In this case, if you access the Clone () method in another class,

is inaccessible because object is not under the same package as the current class.

c) This permission modifier can only be protected, because it guarantees the controllability of the Clone () method

D) It is recommended that when a subclass overrides the Clone () method in the object class, the permission modifier remains protected unless you can guarantee that everything is under control.

5) protected void Finalize (), modifier is protected, can refer to 4)

  Ii. A brief overview of the function of the method

1 registernatives () Private method, registering local method

2 GetClass (), gets the bytecode object, related to the reflection mechanism in Java

3 Hashcode (), providing support for data structures in Java

4 toString (), describing the object

5 Clone (), providing an object clone

6 Notify, Notifyall, and wait methods are related to threads in Java

7 finalize, related to garbage collection

8 equals (), used to determine whether two objects are equal

  The thinking about Object class

1, the use of permission modifiers, when writing programs, seriously think about, use what kind of permission modifier, you really understand the use of permission modifiers?

2, final, native keyword understanding, of course, there are construction methods, static code block, construction code block, static method, static member variable execution order is what? Because we see a static block of code in the object class, we see it and think about it.

3, there is a very interesting question, notify, Notifyall, wait methods these and multithreading-related classes, why set in the object class? A detailed explanation of these methods will be described when multi-threading is introduced.

4. For an answer to a common question, rewrite the Equals () method, why rewrite the Hashcode () method, and you can find the appropriate answer in the JDK source code (which is clearly described above).

5, in the process of learning, must have a deep understanding of the concept of concepts, can not be the same.

  Iv. Summary

The above content from the JDK source code and some of their own views, if there is insufficient or wrong place, but also ask you to advise, common progress. This article is purely original, reproduced please indicate the source, thank you!

Java source Learning-Detailed object class

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.