Home  >  Article  >  Java  >  How to use methods in Java Object class

How to use methods in Java Object class

王林
王林forward
2023-04-18 18:13:11684browse

1. Introduction to the Object class

Object is a class provided by Java by default. Except for the Object class, all classes in Java have inheritance relationships. By default, it will inherit the Object parent class. That is, objects of all classes can be received using the reference of Object.

Example: Use Object to receive objects of all classes

class Person{}
class Student{}
public class Test {
    public static void main(String[] args) {
        function(new Person());
        function(new Student());
    }
    public static void function(Object obj) {
        System.out.println(obj);
    }
}
//执行结果:
Person@1b6d3586
Student@4554617c

So during development, the Object class is the highest unified type of parameters. But the Object class also has some well-defined methods. As follows:

How to use methods in Java Object class

Here are three of the methods: toString() method, equals() method, hashcode() method

2. Rewrite toString Method to print object

When we want to print the contents of the object, we can do it by overriding the toString method in the Object class!

The following explains why the toString() method should be overridden

The following code wants to print a Person object:

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

    }
    public static void main(String[] args) {
        Person person = new Person("Jim","男", 18);
        System.out.println(person);
    }
}

Look at the execution result and the printed content is not the specific content of the object.

How to use methods in Java Object class

Observe the println method source code here. In the source code, the valueOf method in the String class is called. When jumping to the source code at valueOf, you can find that the method body actually The toString method is called again,

How to use methods in Java Object class

Now let’s look at the specific implementation of toString,

How to use methods in Java Object class

getClass() .getName() returns the runtime class (Class) of this Object, and returns the name of the entity (class, interface, array class, basic type or void) represented by this Class object in the form of String

hashCode( ) method returns the "address"

Integer.toHexString(hashCode()) Gets the hash code value of this object (int type), and uses the wrapper class Integer class to get the hash code of this int type value, convert it to a hexadecimal unsigned integer, and represent the converted hexadecimal integer in the form of a string

So the output function println is implemented by calling toString at the bottom level. If you want To realize the specific content of the printing object, we only need to rewrite the toString method in the Object class according to our own ideas

public class Person {
    String name;
    String gender;
    int age;

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

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

    }
    public static void main(String[] args) {
        Person person = new Person("xin","男", 21);
        System.out.println(person);
    }
}

Execution result:

How to use methods in Java Object class

3. Object comparison equals method

In Java, when == is compared:

  • If the left and right sides of == are basic type variables, what is compared is whether the value in the variable is Same

  • If the left and right sides of == are reference type variables, the comparison is whether the reference variable addresses are the same

If you want to compare the contents of the objects , the equals method in Object must be rewritten, because the equals method also compares according to the address by default. The following is the source code of the equals method:

How to use methods in Java Object class

Object comparison code example:

class Person{
    private String name ;
    private int age ;
    public Person(String name, int age) {

        this.age = age ;
        this.name = name ;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false ;
        }
        if(this == obj) {
            return true ;
        }
        //不是Person类对象
        if (!(obj instanceof Person)) {
            return false ;
        }
        Person person = (Person) obj ; // 向下转型,比较属性值
        return this.name.equals(person.name) && this.age==person.age ;
    }

}

public class Test {
    public static void main(String[] args) {
        Person p1 = new Person("xin", 20);
        Person p2 = new Person("xin", 20);
        Person p3 = new Person("rong", 21);

        System.out.println(p1.equals(p2));
        System.out.println(p1.equals(p3));

    }
}

Execution result:

How to use methods in Java Object class

##4. hashCode method

The hashcode method is used to determine whether the location of the object stored in the memory is the same

The function of hashCode() in the hash table is to obtain the hash code of the object and then determine the position of the object in the hash table.

hashCode method source code:

How to use methods in Java Object class

#This method is a native method, the bottom layer is written in C/C code; it cannot be observed in the compiler .

We believe that two objects with the same name and the same age are the same object and should be stored in the same location

Look at the code given below, there is no overriding of the hashCode() method, The two objects have the same content, but the resulting hash values ​​are different:

class Person {
    public String name;
    public int age;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
public class TestDemo4 {
    public static void main(String[] args) {
        Person per1 = new Person("xin", 21) ;
        Person per2 = new Person("xin", 21) ;
        System.out.println(per1.hashCode());
        System.out.println(per2.hashCode());
    }
}

Execution result:

How to use methods in Java Object class

So, if we want to think of two If two objects have the same content and their locations in memory should be equal, the hashCode() method needs to be overridden.

import java.util.Objects;

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

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

public class TestDemo4 {
    public static void main(String[] args) {
        Person per1 = new Person("xin", 21) ;
        Person per2 = new Person("xin", 21) ;
        System.out.println(per1.hashCode());
        System.out.println(per2.hashCode());
    }
}

Execution result:

How to use methods in Java Object class

The above is the detailed content of How to use methods in Java Object class. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete