Object object you really understand it?

foreword

I went home on May 1 and broke another vacation time~~~

Only the bald head can become stronger

Looking back at the front:

It took me a while to learn the basics of multithreading before. It's difficult, difficult, difficult.... I plan to write a thread pool and temporarily stop the multithreading series...

When I was browsing Jianshu at noon today, I found that some big factories would also ask what methods are in the Object object (it can be regarded as a knowledge point). I haven’t reviewed the Object seriously, so this article mainly looks at what the Object object is. The place to pay attention~

Then let's start. If there are mistakes in the article, please bear with me and correct me in the comment area~

1. Introduction to Object

Disclaimer: This article uses JDK1.8

We know Java, Java is an object-oriented language. No matter what appears in Java, it can be considered an object ( except for the eight basic data types. Of course, the eight basic data types can also be boxed into objects):

  • And Object is the highest level of these objects, all Java objects implicitly inherit Object objects (no need to explicitly write extendsinheritance)
  • All Java objects have Object default methods .

So let's see what methods Object has:

In fact, it can be summed up in a few:

  • registerNatives()[Low-level implementation, no research]
  • hashCode()
  • equals(Object obj)
  • clone()
  • toString()
  • notify()
  • notifyAll()
  • wait(long timeout)[There are also two overloaded]
  • finalize()

Object has a total of 11 methods, one of which is the underlying implementation registerNatives(), and two of which are wait()overloaded wait(long timeout, int nanos)methods.

  • So all we really need to look at are 8 methods

There is one more property :


 public final native Class<?> getClass();

Second, equals and hashCode methods

The equals and hashCode methods can be said to be the key questions in the interview. With String, it can be said that they exist in the interview questions .

First, let's take a look at the native implementation of equals and hashCode :

hashCode:


public native int hashCode();

equals:


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

It all looks very simple:

  • hashCode()It is implemented at the bottom of the native method.
  • equals()directly ==determine whether it is equal.

To make it clearer what exactly they do, let's read its comments:

From the comments we can summarize the following points :

  • Overriding methods, methods equals()that must be overriddenhashCode()
  • equals()The method defaults to comparing the address of the object, using the ==equality operator
  • hashCode()The method has the function of improving performance for objects whose underlying layer is a hash table
  • The same object (if the object has not been modified): then repeated calls hashCode()return the same int!
  • hashCode()By default, the method is converted from the address of the object
  • equals()The method also has 5 default principles:
    • Reflexivity---> equals()The call returns true, no matter who calls these two objects equals(), it returns true
    • Consistency--->As long as the object has not been modified, then multiple calls will still return the corresponding result!
    • Transitive ---> x.equals(y)and y.equals(z)both return true, then it can be concluded: x.equals(z)return true
    • Symmetry ---> x.equals(y)and y.equals(x)the result should be equal.
    • The parameter passed in is null, the return is false

hashCode()It is easy to understand why the performance improvement is brought about by using the hash table as the bottom layer. Let's review the insertion of HashMap again:

If the hash values ​​are not equal, then you can directly judge that the key is not equal!

2.1 equals and hashCode method overriding

equals()The method defaults to comparing the addresses of objects, using the ==equality operator. But according to our normal development, it is meaningless to compare the object address .

  • In general, if we have two Address objects, as long as the province, city, and street numbers of these two objects are equal , we consider these two objects equal!

2.2 equals and hashCode methods implemented by String

We may have heard it in the beginning: String already implements equals and hashCode methods.

  • That's why, we can directly use String.equals() to determine whether two strings are equal!

Let's take a look at its implementation:

Three, toString method

Next, let's look at the toString method, which is also very simple:

The toString method is mainly used to identify the object:

We can all see from the above results: we can't see anything in the results ~

So we generally rewrite toString(), then the printed result is very convenient for us to debug !


    @Override
    public String toString() {
        return "Address{" +
                "provinceNo=" + provinceNo +
                ", cityNo=" + cityNo +
                ", streetNo=" + streetNo +
                '}';
    }

The result below looks much better:

Four, clone method

Let's also take a look at its top comment:

After reading the comments above, we can summarize the following points :

  • The clone method is used for object cloning. Generally, the object to be cloned is independent (separate from the original object)
  • A deep copy means that the member variables of the object (if it is a variable reference) should be cloned, and a shallow copy means that the member variables are not cloned.

Let's take a look at the shallow copy: the Employee object is copied, but its member variable Hireday is not cloned, so it still points to the same Date object !

4.1 clone usage

So how do we clone objects? Whether it is a shallow copy or a deep copy, it is two steps:

  1. The cloned object must implement the Cloneable interface
  2. Override the clone method , it is best to modify it as public

Shallow copy : Only the Person object is copied, and the date is not copied!


public class Person implements Cloneable {

    // 可变的成员变量
    private Date date;

    @Override
    public Object clone() throws CloneNotSupportedException {

        return super.clone();
    }

}

Deep copy : not only copies the Person object, but also copies the date member variable


public class Person implements Cloneable {

    // 可变的成员变量
    public  Date date;

    @Override
    public Object clone() throws CloneNotSupportedException {


        // 拷贝Person对象
        Person person = (Person) super.clone();

        // 将可变的成员变量也拷贝
        person.date = (Date) date.clone();


        // 返回拷贝的对象
        return person;
    }

}

4.2 clone question further study protected

I don't know if anyone has the same question as me :

  • I only want a shallow copy , can I directly call .clone() on the object to achieve this ?

For example, I now have an Address object:


public class Address  {

    private int provinceNo;
    private int cityNo;
    private int streetNo;

    public Address() {
    }

    public Address(int provinceNo, int cityNo, int streetNo) {
        this.provinceNo = provinceNo;
        this.cityNo = cityNo;
        this.streetNo = streetNo;
    }
}

What do you think of the code below ?


    Address address = new Address(1, 2, 3);
    address.clone();

we all know:

  • Classes and properties modified by protected are visible to themselves, this package and its subclasses

You may think : clone()the method is defined on the Object class (modified with protected), and our custom Address object implicitly inherits Object (all objects are subclasses of Object), then the subclass calls Object to protect clone()It's perfectly fine to retouch

  • However, the IDE reality tells me that this compilation will not pass !

The reason for the error occurred to me immediately: Am I biased against the protected modifier?

Classes and properties modified by protected are visible to themselves, this package and its subclasses. This sentence itself is not wrong. But it also needs to be added : For protected members or methods, whether the molecular class and the superclass are in the same package . A subclass that is not in the same package as the base class can only access protected members that it inherits from the base class, not the protected members of the base class instance itself .

  • The above code is wrong: Address and Object are not in the same package , and Address directly accesses Object's clone method. This will not work.

Let me take a screenshot of two pictures and show them to you (after reading the pictures and then reading the description above, you can understand):

Image source and more expanded reading : https://blog.csdn.net/wangyanguiyiyang/article/details/49800493

Five, wait and notify methods

The wait and notify methods are actually the APIs that Java provides us to communicate between threads .

As usual, let's see what the comments say:

wait method:

notify method:

notifyAll() method:

After reading the comments above, we can summarize the following points :

  • Whether wait, notify or notifyAll() needs to be called by the listener object (lock object)
    • In short: they are all called in a synchronized block of code , otherwise an exception will be thrown!
  • notify()Wake up a thread waiting in the queue (not sure which one will wake up), wake up all threads notifyAll()waiting in the queue
  • There are 4 situations that cause wait()the thread to be woken up
    • the thread is interrupted
    • wait()Time is up
    • notify()wake up
    • notifyAll()wake up
  • The calling wait()thread releases the lock

In fact, after summarizing the above, there will not be a deep impression. You can try to answer a few questions to deepen your understanding of wait()and notify().

5.1 Why wait and notify are on the Object method?

We have said from the beginning: wait()and notify()is the API that Java provides us with communication between threads. Since it is a thread, what is defined on the Object class instead of the Thread class?

Because our lock is an object lock [if you forget it, you can review it: Learn about the Java lock mechanism ], every object can become a lock. Let the current thread wait for the lock of an object, of course, it should be operated through this object .

  • Lock objects are arbitrary , so these methods must be defined in the Object class

5.2 What happens after the notify method is called?

As mentioned above, notify will wake up a thread that is waiting in the queue.

But note that:

  • After the notify method is called, the awakened thread will not immediately obtain the lock object . Instead, the lock object will be obtained after the synchronized code block of notify is executed .

5.3 What is the difference between sleep and wait?

Thread.sleep()Both can suspend the current thread and Object.wait()release CPU control.

  • The main difference is that the control of the object lock isObject.wait() released at the same time as the CPU is released .
  • without Thread.sleep()releasing the lock

References:

Six, finalize () method

finalize()The method will be called before the garbage collector clears the object , but the method does not know when it will be called, which is indeterminate

  • Usually we don't rewrite it~

The finalize() method of an object will only be called once , and the finalize() call does not mean that gc will recycle the object immediately, so it is possible that after finalize() is called, the object does not need to be recycled, and then the real When it is about to be recycled, because it has been called once before, finalize() will not be called, causing problems.

References:

Advanced information:

7. Summary

In general, I have read Object once, so I don’t forget its method all at once~~~ I also encountered problems in the process of learning. The most obvious thing is to deepen the protected modifier again. understand.

References:

  • "Java Core Technology Volume 1"

If there are any mistakes in the article, please correct me, and we can communicate with each other. Students who are used to reading technical articles on WeChat and want to get more Java resources can follow WeChat public account: Java3y . For everyone's convenience, I just created a new QQ group: 742919422 , you can also go to communicate. Thank you for your support! Hope to introduce more to other friends in need

Table of Contents Navigation for Articles :

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325212273&siteId=291194637