Object The source code parsing

Java It is an object-oriented language , stay Java Everything in it can be seen as an object , and Java All objects in it inherit from by default Object class , So brother dog reviewed this class today .

Object  Method Overview

The picture above shows Object Altogether 12 A way , among registerNatives() By C The realization of language , This is outside the scope of the study .


     * Returns the runtime class of this {@code Object}. The returned
     * {@code Class} object is the object that is locked by {@code
     * static synchronized} methods of the represented class.
public final native Class<?> getClass();

The function of this method is to return the runtime class of an object , Its return value is Class type ,Class c = obj.getClass(); Through object c , We can get all the member methods of the object , Each member method is a Method object ; We can also get all the member variables of the object , Each member variable is a Field object ; alike , We can also get the constructor of this object , The constructor is a Constructor object . This method is often used in reflection .


     * Returns a hash code value for the object. This method is
     * supported for the benefit of hash tables such as those provided by
     * {@link java.util.HashMap}.
    public native int hashCode();

This method has a long comment , I won't let it out . NOTE indicates :

  • hashCode Method returns the hash value .
  • The return value is converted from the address of the object by default .
  • The same object calls hashCode The return value of is equal .
  • two-object equals equal , that hashCode Must be equal .
  • two-object equals It's not equal , that hashCode It doesn't have to be the same .


public boolean equals(Object obj) {
    return (this == obj);

equals The implementation of is very simple , Its purpose is to compare whether two objects are equal , The comparison is based on the memory address of the two . besides ,equals Also follow the following principles :

1、 reflexivity :x.equals(x);  // true
2、 symmetry :x.equals(y) == y.equals(x);  // true
3、 Transitivity :if (x.equals(y) && y.equals(z))
            x.equals(z); // true;

4、 Uniformity , As long as the object is not modified , Multiple calls  equals()  Method result unchanged :
x.equals(y) == x.equals(y); // true 

5、 Non emptiness , Student: yeah any not  null  The object of  x  call  x.equals(null)  The result is  false :
x.equals(null); // false;

Why rewrite hashcode and equals ?

This question has been shared before :https://mp.weixin.qq.com/s/iIoAnneaeHdQYrj9sd_yZA


protected native Object clone() throws CloneNotSupportedException;

clone() yes Object Of protected Method , It is not public, A class is not explicitly overridden clone(), No other class can directly call an instance of that class clone() Method . Besides ,Clone Some important points are also mentioned in the notes of :

  • Cloned objects must be implemented Cloneable Interface and override clone Method , Otherwise it will be reported CloneNotSupportedException abnormal
  • clone() The method is not Cloneable Interface method , It is Object One of the protected Method .Cloneable Interfaces are just rules , If a class is not implemented Cloneable The interface is called again clone() Method , Will throw CloneNotSupportedException.
  • Shallow copy : The copy object and the reference type of the original object refer to the same object .
  • Deep copy : The reference types of the copied object and the original object refer to different objects .

Detailed explanation of shallow copy and deep copy , Please read this old article :


public String toString() {
       return getClass().getName() + "@" + Integer.toHexString(hashCode());

This method should have nothing to say , Native toString Method just returns , Object name + its hashCode , But anyone who has done development knows , Native toString Not much . We need to rewrite toString Generally, it is convenient for debugging , You need to know the property value of the object , Not just hashCode . therefore , It should be rewritten as follows :

public class Student {

    private int age;

    private String name;

    //  Omit  get、set

    public String toString() {
        return "Student{" +
                "age=" + age +
                ", name='" + name + '\'' +

6、notify and wait

public final native void notify();
public final native void notifyAll();

First of all notify , The notes will not be posted ,notify Its function is to wake up a thread in the waiting queue at random , and notifyAll Is to wake up all threads waiting in the queue .

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 {
        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) {


And then there was wait ,wait Its function is to let the current thread enter the waiting state , meanwhile ,wait() It also causes the current thread to release the lock it holds . Until another thread calls the notify() Method or notifyAll() Method , The current thread is awakened to the ready state .

wait(long timeout) ( In Milliseconds ) Leave the current thread waiting ( Blocking ) state , Until another thread calls the notify() Method or notifyAll() Method , Or more than the specified amount of time , The current thread is awakened to the ready state .

wait(long timeout, int nanos) and wait(long timeout) Function as , The only difference is that this can provide higher precision . Total timeout ( In nanoseconds ) The calculation for the 1000000 *timeout+ nanos.By the way ,wait(0,0) and wait(0) The effect is the same .

besides ,notify and wait There's another paragraph in the comment :

* <p>
     * This method should only be called by a thread that is the owner
     * of this object's monitor. A thread becomes the owner of the
     * object's monitor in one of three ways:
     * <ul>
     * <li>By executing a synchronized instance method of that object.
     * <li>By executing the body of a {@code synchronized} statement
     *     that synchronizes on the object.
     * <li>For objects of type {@code Class,} by executing a
     *     synchronized static method of that class.
     * </ul>
* <p>

See this English , I'm shivering after grade four . The above notes mainly describe ,notify and wait The use of methods . It means that both of them must be in synchronized Decorated synchronization method or synchronization code used in .

  • Why? wait() Must be in sync (Synchronized) Method / Call in code block ?

answer : call wait() Just release the lock , The premise of releasing the lock is to obtain the lock first , Get the lock before you release it .

  • Why? notify()、notifyAll() Must be in sync (Synchronized) Method / Call in code block ?

answer :notify()、notifyAll() Is to give the lock to contain wait() Method thread , Let it go on , If you don't have a lock , How to give the lock to other threads ?( The essence is to let threads in the entry queue compete for locks )

Please refer to this blog for details :https://blog.csdn.net/qq_42145871/article/details/81950949

  • Thread.sleep() and Object.wait() What's the difference? ?

First , Both can pause the current thread , Release CPU control power . The main difference is this Object.wait() Releasing CPU meanwhile , Release the object lock control . and Thread.sleep() No release of lock . let me put it another way sleep It's just being a hoodlum. , It's not shit to occupy the manger .


If you see this , Like this article , Please forward 、 give the thumbs-up . WeChat search 「 A good loser 」, Welcome to your attention .

reply 「1024」 Send you a complete set java、python、c++、go、 front end 、linux、 Algorithm 、 big data 、 Artificial intelligence 、 Small program and English Course .

reply 「 e-book 」 Send you 50+ Ben java e-book .

 programing language