Why is the Object class so strong?

Digression

Everything has roots. I got on the revolutionary boat, and no one can get off. Yesterday, I saw my grandma from the hospital and was full of emotions. I am old and have fragile bones. I push the beds between the floors and watch all kinds of things. Looking at their uncomfortable look, the pressure of the atmosphere makes it difficult for me to breathe. There are many pictures in my mind. Young people should share their love with themselves in the process of struggle, and remember to take care of themselves.

Object

What is the Object class? (You can't call me Dad too much!)

The class Object is the root of the class hierarchy. Every class has Object as a super class. All objects (including arrays) implement such methods. If a class does not explicitly inherit a parent class, then it is a subclass of Object; excellent is excellent, and it is also sensible. Obeject is under the java.lang package. When you use it, you don’t need to guide the package. Say irritating or not?

//啥意思呢? 就是
	class Son{
    
    }
	//等价于
	class Son extends Object{
    
    }

This is not even more exaggerated.What is more exaggerated is that it can also receive all kinds of objects, which is too particular.

public class Demo01 {
    
    
    public static void main(String[] args) {
    
    
        Object food = new Food();
        Object meat = new Meat();
    }
}
class Food{
    
    }
class Meat{
    
    }

What can it do? (its method)

Let's take a look at the rhetoric of the JDK:
Insert picture description here
look at the method in the source code:

	//返回此 Object的运行时类
	public final native Class<?> getClass();
	//用于哈希查找
	public native int hashCode();
	//用于比较指示 某个其他对象是否“等于”此对象
 	public boolean equals(Object obj) {
    
    
        return (this == obj);
    }
    //保护方法,实现对象的浅复制,只有实现了Cloneable接口才可以调用该方法,否则抛出CloneNotSupportedException异常。
 	protected native Object clone() throws CloneNotSupportedException;
 	public String toString() {
    
    
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
    //该方法唤醒在该对象上等待的某个线程。
    public final native void notify();
    //该方法唤醒在该对象上等待的所有线程
    public final native void notifyAll();
    //wait方法就是使当前线程等待该对象的锁,当前线程必须是该对象的拥有者,也就是具有该对象的锁。wait()方法一直等待,直到获得锁或者被中断。wait(long timeout)设定一个超时间隔,如果在规定时间内没有获得锁就返回。此时该线程就可以被调度了,如果是被中断的话就抛出一个InterruptedException异常。
    public final void wait() throws InterruptedException {
    
    
        wait(0L);
    }
    public final native void wait(long timeoutMillis) throws InterruptedException;
    rotected void finalize() throws Throwable {
    
     }
    public final void wait(long timeoutMillis, int nanos) throws InterruptedException {
    
    
        if (timeoutMillis < 0) {
    
    
            throw new IllegalArgumentException("timeoutMillis value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
    
    
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos > 0) {
    
    
            timeoutMillis++;
        }

        wait(timeoutMillis);
    }

What we usually use more is nothing more than comparison and the toString() method.

If we don’t print the toString() method directly, is it Hana? In the source code, we can find that through reflection, we have obtained the fully qualified class name and @hexadecimal hash value string of the current object. This is what will be printed directly without rewriting toString().

package week.third.test;

public class Demo02 {
    
    
    public static void main(String[] args) {
    
    
        Object s = new Student();
        System.out.println(s);
        //week.third.test.Student@49e4cb85
        
    }
}
class Student {
    
    }

Now let's operate it.

public class Demo01 {
    
    
    public static void main(String[] args) {
    
    
        Object person = new Person("张三",18);
        Object person1 = new Person("张三",18);
        //演示: equals();  false
        System.out.println(person.equals(person1));

        //演示: toSting();  Person{Name='张三', age=18}
        System.out.println(person.toString());

    }
}
class Person{
    
    
    public String getName() {
    
    
        return Name;
    }

    public Person(String name, int age) {
    
    
        Name = name;
        this.age = age;
    }

    public Person() {
    
    
    }

    public void setName(String name) {
    
    
        Name = name;
    }

    private String Name;

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }

    @Override
    public String toString() {
    
    
        return "Person{" +
                "Name='" + Name + '\'' +
                ", age=" + age +
                '}';
    }

    private int age;


}

At this time, the problem is found. It is obviously the same. Why is it false? By calling the equals() method directly, the address of the two objects is compared by default. Even when the properties of the object are the same, it will return false. This source code also has an explanation.

To untie the bell, you still need to tie the bell, and you also need to rewrite the comparison method so that you can judge the attribute. After the renewal, it returns true. Therefore, when comparing the reference type data, you should first overwrite equals( ) Method, otherwise the heap memory address values ​​of the two objects will be compared, which will not be equal.

 @Override
    public boolean equals(Object o) {
    
    
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age && Objects.equals(Name, person.Name);
    }

Originality is not easy, I hope the guest officer, give me a chance!

Insert picture description here

Guess you like

Origin blog.csdn.net/AzirBoDa/article/details/112862710