Object of Java Common API

1. Introduction to the Object class

Class Object is the root of the class Object structure. Every class has Object as a super class. In Java, only the basic data types are not objects and do not inherit the Object class. All other objects (including arrays) implement the methods of this class.
Define a Java class as follows:

public class Demo{
    
    
    //测试类
}

Define a Java class that inherits Object as follows:

public class Demo extends Object{
    
    
    //测试类
}

These two classes are exactly the same, because if a class does not specify which parent class to inherit from, the Object class is inherited by default.

There is an empty constructor in the Object class:

public Object()

All objects can be accepted using the Object type:

public class Demo {
    
    
    public static void main(String[] args) {
    
    
        Object ob1=new Person();
        Object ob2=new Dog();
    }
}
class Person{
    
    
    public Person(){
    
    
        System.out.println("Person().....");
    }
}
class Dog{
    
    
    public Dog(){
    
    
        System.out.println("Dog().....");
    }
}

Output result:

Person().....
Dog().....

2. Common methods of Object class

2.1equals() method

Use == in basic data types to compare whether the values ​​of two basic data types are equal.
The comparison of objects uses the equals() method to compare whether two objects are equal.
The equals() method in the bottom layer of Object:

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

It can be seen that the meaning of the equals() method is to indicate whether some other objects are equal to this.
Take an example to prove that the equals() method compares two objects instead of values:

public class Demo {
    
    
    public static void main(String[] args) {
    
    
        Person p1=new Person(20,"Ning");
        Person p2=new Person(20,"Ning");
        System.out.println(p1.equals(p2));
    }
}
class Person{
    
    
    private int age;
    private String name;
    public Person(){
    
    

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

The result of code execution is false. At this time, some people will be puzzled. It is clear that the two class member variables are the same. Why is it still outputting false? The reason is that equals compares the addresses of the two objects p1 and p2. In the code New twice, so two objects are created in the heap memory. Obviously the addresses of these two objects are not the same, so false will be output.

Then someone will ask how to use the equals() method to compare whether the member properties of two objects are the same, which requires rewriting the equals() method in the class to achieve:

public class Demo {
    
    
    public static void main(String[] args) {
    
    
        Person p1=new Person(20,"Ning");
        Person p2=new Person(20,"Ning");
        System.out.println(p1.equals(p2));
    }
}
class Person{
    
    
    private int age;
    private String name;
    public Person(){
    
    

    }
    public Person(int age,String name){
    
    
        this.age=age;
        this.name=name;
    }
    public boolean equals(Person p){
    
    
        if(this.age!=p.age){
    
    
            return false;
        }
        else if(this.name!=p.name){
    
    
            return false;
        }else {
    
    
            return true;
        }

    }
}

The output of this code execution result is true.

The equals method implements the equivalence relationship on non-null object references:

  • Reflexivity: For any non-empty reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference value x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • Transitivity: For any non-null reference value x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference value x and y, multiple calls to x.equals(y) always return true or always return false, and no information used in the setting of equals compared to the object is modified.
  • For any non-empty reference value x, x.equals(null) should return false.

2.2toString() method

The toString() method returns the string representation of the object. Generally speaking, the toString method returns a string that "textually represents" this object. The result should be a concise expression that is easy for people to read. It is recommended that all subclasses override this method.
The toString class method Object returns an unsigned hexadecimal representation of the name of the class by which the object is an instance, the symbol character `@" and the hash code of the object. In other words, this method Return a string equal to the following values: getClass().getName() +'@' + Integer.toHexString(hashCode()) The
source code of the toString() method in the Object class:

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

Example:

public class DemoToString {
    
    
    public static void main(String [] args){
    
    
        Object o1=new Object();
        Object o2=new Object();
        System.out.println(o1.toString()+'\n'+o2.toString());
    }
}

Output result:

java.lang.Object@1b6d3586
java.lang.Object@4554617c

The output result is: object type + @ + memory address value, but in our actual development process, we often want to see the output form of the attribute corresponding to the string, so we need to rewrite toString():

public class Demo {
    
    
    public static void main(String[] args) {
    
    
        Person p1=new Person(20,"Ning");
        System.out.println(p1.toString());
    }
}
class Person{
    
    
    private int age;
    private String name;
    public Person(){
    
    

    }
    public Person(int age,String name){
    
    
        this.age=age;
        this.name=name;
    }
    @Override
    public String toString() {
    
    
        return "Person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

Output result:

Person{age=20, name='Ning'}

Here we can also directly output the object p1, and we can also call the toStirng() method because of the println() method in the System class:

public void println(Object x) {
    
    
        String s = String.valueOf(x);
        synchronized (this) {
    
    
            print(s);
            newLine();
        }
    }
public static String valueOf(Object obj) {
    
    
    return (obj == null) ? "null" : obj.toString();
}

If an object is passed in, the toString() method will be called by default.

2.3 Other methods

  • clone() Return value type and decoration: protected Object
    creates and returns a copy of this object.
  • finalize() Return value type and modification: protected void
    When the garbage collection determines that there is no longer a reference to the object, the garbage collector calls the object on the object.
  • getClass() Return value type and decoration: Class<?>
    returns the runtime class of this Object.
  • hashCode() Return value type: int
    returns the hash code value of the object.
  • notify() Return value type: void
    wakes up a single thread that is waiting for the object monitor.
  • notifyAll() Return value type: void
    wakes up all threads waiting for the object monitor.
  • wait() Return value type: void
    causes the current thread to wait until another thread calls the notify() method or notifyAll() method of the object.
  • wait(long timeout) Return value type: void
    causes the current thread to wait until another thread calls the notify() method or the object's notifyAll() method, or the specified time has passed.
  • wait(long timeout, int nanos) Return value type: void
    causes the current thread to wait until another thread calls the notify() method or notifyAll() method of the object, or some other thread interrupts the current thread, or a certain amount of real-time time.

Guess you like

Origin blog.csdn.net/weixin_45772185/article/details/115263943
Recommended