How is the toString method used in Java?

The toString method in Java is used to convert an object into a string representation. By default, every class inherits from the Object class, where the toString method will return a string representation of an object in the format of classname@hashcode.

If we want to customize the toString method of a class, we can override this method in the class. For example:

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

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

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

    public static void main(String[] args) {
        Person person = new Person("Tom", 20);
        System.out.println(person.toString());  // 输出:Person{name='Tom', age=20}
    }
}

In the example above, we have rewritten the toString method of the Person class to return the object’s properties as a string. This way, when calling the toString method, we can get the output we expect.

Leave a Reply 0

Your email address will not be published. Required fields are marked *