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().
toStringhelps youtoStringmethod for you object