Introduction to the use of the Java Object class

One, Object class overview

  • The Object class is the parent class of all classes. All classes in Java directly and indirectly inherit the Object class.
  • If a class does not specify a parent class, then the Object class is inherited by default

Two, toString method

Returns the string representation of this object.
Usually, the toString method returns a string that "represents" this object as text.
The result should be a concise but easy-to-read information expression.

1. Method summary

Method information:
public String toString()
returns:
the string representation of the object.

2. Rewrite the toString method

Why rewrite the toString method

When printing an object name, ifDo not override the toString method, Then willPrint out the address value of the object, It is of little significance in actual use, which is determined by the Object class. If you want to change the information you want to print, you must rewrite the toString method.

Code example

New Person class

public class Person [extends Object]{
    
    
    private String name;
    private int age;

    public Person() {
    
    }
    public Person(String name, int age) {
    
    this.name = name;       this.age = age;}
    public String getName() {
    
    return name;}
    public void setName(String name) {
    
    this.name = name;}
    public int getAge() {
    
    return age;}
    public void setAge(int age) {
    
    this.age = age;}

    /*
    直接打印对象的地址值没有意义所以要重写Object类的toString方法
     */
    @Override
    public String toString() {
    
    
        return "Person{name = "+ name+",age = "+age +"}";
    }
    //toString也可以使用集成开发环境直接生成
}

Create a new test class, use the toString method

public class TestToString{
    
    
    public static void main(String[] args) {
    
    
        //Person类默认继承Object类,所以我们可以使用Object类的toString方法(返回值为String)
        Person p = new Person("张三丰",18);
        //如果在Person中没有重写toString方法,则打印对象的地址值
        //如果在Person对toString方法进行了重写,则按照指定格式打印
        System.out.println(p.toString());
        System.out.println(p);
    }
}

【tips】

See if a class has overridden the toString method, and print the object name
directly . If the address value is printed directly, the name does not override the toString method.
If the toString method is overridden, the output will be output in the specified format

Three, equals method

Instructions 其他某个对象是否与此对象“相等”.
Source code:
public boolean equals (Object obj){ return (this == obj); }

1. Method summary

Method information:
public boolean equals(Object obj)
Parameters:
obj-the reference object to be compared with.
Return:
If this object is the same as the obj parameter, then return true; otherwise, return false.

2. The default address value comparison

Continue to use the above Person class

Create a new test class, use the equals method

public class TestEquals {
    
    
    public static void main(String[] args) {
    
    
        /*
        Person类默认继承Object类,所以可以使用equals方法,指示另外一个对象与当前对象是否相等
         */
        Person p1 = new Person("张三",18);
        Person p2 = new Person("李四",20);
        System.out.println(p1.equals(p2));//打印结果:false

        //把p2赋值给p1
        p1 = p2;
        System.out.println(p1.equals(p2));//打印结果:true
    }
}

【tips】

For 基本数据类型comparison is
to 引用数据类型compare is地址值

3. Object content comparison

Like the toString method, the equals method also uses the address value for comparison, which is of little significance. To be 进行对象属性的比较,依旧需要重写equals方法.

Rewrite the equals method in the Person class (integrated development environment can also be generated, it is recommended to write it by yourself to experience the principle)

    @Override
    public boolean equals(Object obj) {
    
    
        //增加判断,如果对象参数为自己,直接返回true
        if(obj == this){
    
    
            return true;
        }
        //增加判断,如果对象为空,直接返回false,提高程序运行效率
        if(obj == null){
    
    
            return false;
        }
        //增加判断,防止类转换异常
        if(obj instanceof Person){
    
    
            //使用向下转型,才可以使用子类特有的属性和方法
            Person p = (Person)obj;
            //比较两个对象的属性
            boolean b = this.name.equals(p.name) && this.age == p.age;
            return b;
        }

Modify the test class

public class TestEquals {
    
    
    public static void main(String[] args) {
    
    
        /*
        Person类默认继承Object类,所以可以使用equals方法,指示另外一个对象与当前对象是否相等
        源码:
        public boolean equals (Object obj){
            return (this == obj);
        }
         */
        Person p1 = new Person("张三",18);
        Person p2 = new Person("张三",18);
        System.out.println(p1.equals(p2));//打印结果:true
        //虽然是两个对象,但是他们的内容一样。
        //根据我们重写的equals方法,所以返回true
}

Fourth, the Objects class

Starting from jdk1.7, there is the Objects class

The basic information of the
class public final class Objects extends Object
This class consists of some static methods and is declared as the final class cannot be inherited by other classes.
These methods are null-safe (null pointer safe) or null (tolerant of null pointers) methods.
Calculate the hashcode of the object, return a string for the object, and compare the two objects.

public class DemoObjects {
    
    
    public static void main(String[] args) {
    
    
        String str1 = null;
        String str2 = "csdn";

        //使用String类的equals方法比较
        System.out.println(str1.equals(str2));//发生空指针异常,代码报错

        //使用Objects类的equals方法比较
        System.out.println(Objects.equals(str1,str2));//程序正常运行,false
    }
}

Guess you like

Origin blog.csdn.net/weixin_44580492/article/details/107326725