How do you directly print an object in Java?

In Java, an object can be printed directly by calling its toString() method. This method belongs to the Object class, which is inherited by all Java classes, allowing them to utilize the toString() method.

By default, invoking the toString() method will return a string containing the class name and memory address. If you want to customize the printed content, you can override the toString() method in the class.

Here is an example:

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

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

    // 重写toString()方法
    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }

    public static void main(String[] args) {
        Person person = new Person("Alice", 25);
        System.out.println(person); // 直接打印对象
    }
}

The output is:

Person [name=Alice, age=25]
Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds