Moment For Technology

Do you really understand the Object?

Posted on Jan. 31, 2023, 1:03 p.m. by Alice Burns
Category: The back-end Tag: The back-end java The source code Java EE


May Day home and break more a holiday time ~~~

Only a bald head can be strong

To recap:

Before spend a point between the time to engage in multithreaded basic knowledge, difficult ah difficult ah difficult.... I'm going to write about thread pools, but I'm going to stop the multithreading series for now...

Today noon when browsing Jane books found some big factory will also ask the Object Object there is what method (also is a knowledge point), Object I have not gone to seriously review, so this article mainly look at the Object Object has what to pay attention to ~

So let's get started. If there are any mistakes in this article, please feel free to correct them in the comments section

Introduction to Object

Disclainer: This article uses JDK1.8

We all know that Java is an object-oriented language. Whatever appears in Java is considered an object (except for the eight basic data types). Of course, the eight basic data types can also be boxed as objects) :

  • Object is the highest level of these objects, and all Java objects areimplicitInherits Object objects (without display write)extendsInheritance)
  • All Java objects have the Object default method.

So let's see what methods Object has:

In fact, it can be summarized as follows:

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

There are 11 methods for Object, one of which is the low-level registerNatives(), and two wait() and wait(long timeout, int nanos) override methods.

  • So what we really need to look at are 8 ways

One more property:

 public final nativeClass?  getClass();Copy the code

The equals and hashCode methods

The equals and hashCode methods are a big part of the interview question, along with String.

First, let's look at the natively implemented equals and hashCode in Object:


public native int hashCode(a);

Copy the code


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

Copy the code

It all looks pretty simple:

  • hashCode()Implemented by native method base.
  • equals()It directly= =Check if it's equal.

To get a better idea of what they do, read the notes:

According to the notes, we can summarize the following main points:

  • rewriteequals()Method must be overriddenhashCode()The method of
  • equals()The default method is to compare the address of the object, using= =Equivalent operator
  • hashCode()The hash method improves performance for objects that are underlying hash tables
  • Same object (if it has not been modified) : then repeat the callhashCode()Then the int returned is the same!
  • hashCode()Method is converted from the address of the object by default
  • equals()Methods also have five default principles:
    • Reflexivity -- callequals()Returns true regardless of who calls the two objectsequals()All right, return true
    • Consistency -- As long as the object has not been modified, the multiple calls still return the corresponding result!
    • Transitivity -- -x.equals(y)andy.equals(z)Return true, then we can get:x.equals(z)Returns true
    • Symmetry -- - x.equals(y)andy.equals(x)It should be equal.
    • The argument passed in is null and false is returned

It's easy to see why hashCode() brings performance improvements to the underlying hash table. Let's review HashMap inserts again:

If the hash values are not equal, then the key is not equal.

2.1 Equals and hashCode methods overridden

The equals() method defaults to comparing the addresses of objects, using the == equivalence operator. But in our normal development, it doesn't make sense to compare object addresses.

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

2.2String implements equals and hashCode methods

We've probably heard this before: String already implements equals and hashCode methods.

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

Let's take a look at its implementation:

ToString method

Now let's look at the toString method, which is also quite simple:

The toString method is used primarily to identify the object:

We can see from the above results: the results we can not see anything ~

So we usually overwrite toString(), and the printed result is easy to debug!

    public String toString(a) {
        return "Address{" +
                "provinceNo=" + provinceNo +
                ", cityNo=" + cityNo +
                ", streetNo=" + streetNo +
                '} ';
Copy the code

The following results look much better:

4. Clone method

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

After reading the above notes, we can summarize the following key points:

  • The Clone method is used to clone objects, which are usually independent (separate from the original object).
  • A deep copy means that all of the object's member variables (if mutable references) should be cloned, and a shallow copy means that none of the member variables have been cloned

The Employee object is copied, but its member hireday is not cloned, so it points to the same Date object!

4.1 clone usage

So how do we clone objects? There are two steps for both shallow and deep copies:

  1. The cloned object implements the Cloneable interface
  2. Rewrite the clone method, preferably public

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

public class Person implements Cloneable {

    // Variable member variables
    private Date date;

    public Object clone(a) throws CloneNotSupportedException {

        return super.clone(); }}Copy the code

Deep copy: Not only the Person object is copied, but also the date member variable

public class Person implements Cloneable {

    // Variable member variables
    public  Date date;

    public Object clone(a) throws CloneNotSupportedException {

        // Copy the Person object
        Person person = (Person) super.clone();

        // Copy mutable member variables as well = (Date) date.clone();

        // Return the copied object
        returnperson; }}Copy the code

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 just call the.clone() object?

Let's say I now have an Address object:

public class Address  {

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

    public Address(a) {}public Address(int provinceNo, int cityNo, int streetNo) {
        this.provinceNo = provinceNo;
        this.cityNo = cityNo;
        this.streetNo = streetNo; }}Copy the code

What do you think of the following code?

    Address address = new Address(1.2.3);

Copy the code

We all know:

  • Protected classes and properties that are visible to themselves, the package, and their subclasses

You might think: The clone() method is defined on the Object class (protected), and our custom Address Object implicitly inherits Object(all objects are subclasses of Object). It is perfectly fine for subclasses to call Object to protect clone()

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

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

There is nothing wrong with the statement that protected classes and properties are visible to you, the package, and its subclasses. However, there is a caveat: for protected members or methods, whether the molecular class and superclass are in the same package is required. Subclasses that are not in the same package as the base class can access only the protected members they inherit from the base class, not the protected members of the base class instance itself.

  • Address and Object are not in the same package, and Address accesses the Clone method of Object directly. It won't do.

Let me take a screenshot of two images and show them to you (after viewing the images and looking at the description above, you will understand) :

Source images and more reading:

Wait and notify

Wait and notify are essentially apis that Java gives us to communicate between threads.

As usual, let's look at the comments:


Notify method:

NotifyAll () method:

After reading the above notes, we can summarize the following main points:

  • Either wait, notify, or notifyAll() is requiredThe call is made by the listener object (lock object)
    • Simply put: they are all called in a synchronized block of code, otherwise an exception will be thrown!
  • notify()The ones that wake up are those that are waiting in the queueaThread (not sure which one will wake up),notifyAll()What wakes up is the wait queueallthread
  • Lead towait()There are four ways in which a thread can be awakened
    • The thread is interrupted
    • wait()It's time for
    • benotify()Wake up the
    • benotifyAll()Wake up the
  • callwait()The thread will beRelease the lock

Wait () and notify() : Wait () : Wait () : Wait () : wait() : wait()

5.1 Why Wait and notify on Object methods?

Wait () and notify() are apis that Java provides for threads to communicate with each other. What is defined on the Object class instead of the Thread class?

Since our lock is an object lock, every object can be a lock. Making the current thread wait for a lock on an object is, of course, the way to do it.

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

5.2 What Happens after the notify method is invoked?

As mentioned above, notify wakes up a thread that is on a waiting queue.

But be warned:

  • After the notify method is called, the awakened thread does not immediately acquire the lock object. Instead, the lock object is acquired after notify's synchronized block completes execution

5.3 What is the difference between "sleep" and "wait"?

Thread.sleep() and Object.wait() both suspend the current Thread, freeing CPU control.

  • The main difference isObject.wait()While releasing the CPU,Release control of the object lock.
  • whileThread.sleep()No lock release


Finalize () method

The Finalize () method will be called before the garbage collector clears the object, but the method does not know when to call, so it is indeterminate

  • We don't normally rewrite it

Finalize () method of an object will only be called once, and when Finalize () is called, it does not mean that GC will immediately recycle the object, so it is possible that after Finalize () is called, the object will not need to be recycled, and then it is time to be recycled, because it was called once before. Therefore, finalize() will not be called, causing problems.


Advanced information:


I also encountered some problems in the process of learning, most notably a deeper understanding of the protected modifier.


  • Java Core Technology Volume 1

If the article has the wrong place welcome to correct, everybody exchanges with each other. Students who are used to reading technical articles on wechat and want to get more Java resources can follow the wechat public account :Java3y.

Article table of Contents navigation:

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.