简体   繁体   中英

java define println for class object

In C++, one can implement the ostream operator << to be able to define how a class can be output to the stream cout << Class .

Is it possible in java to do something like out.println(Class) ?

System.out.print() calls the toString() method of the object passed to it. If you override the toString() method in your class, you can implement a custom behaviour there. Your class inherit the method from Object . Every class has Object as a superclass in java. Below is the default implementation.

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

The print method ( System.out.print(Object obj) ) looks like this

public void print(Object obj) {
    write(String.valueOf(obj));
}

and the String.valueOf(Object obj) method finally calls toString() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM