public class Card {
private Rank rank;
private Suit suit;
public Card(Rank r, Suit s) {
this.suit = s;
this.rank = r;
}
@Override
public String toString() {
return rank + " of " + suit;
}
public static void main (String[] args) {
Card test = new Card(Rank.A, Suit.Clubs);
System.out.println(test);
}
}
So in my output I have printed A of Clubs. But nowhere am I using toString() I am only defining a new Card from my constructor. So can someone explain to my why I get this output?
If you look at the Javadoc and source for PrintWriter.println(Object) you see
/**
* Prints an Object and then terminates the line. This method calls
* at first String.valueOf(x) to get the printed object's string value,
* then behaves as
* though it invokes <code>{@link #print(String)}</code> and then
* <code>{@link #println()}</code>.
*
* @param x The <code>Object</code> to be printed.
*/
public void println(Object x) {
String s = String.valueOf(x);
synchronized (lock) {
print(s);
println();
}
}
In turn, String.valueOf(Object) does
/**
* Returns the string representation of the {@code Object} argument.
*
* @param obj an {@code Object}.
* @return if the argument is {@code null}, then a string equal to
* {@code "null"}; otherwise, the value of
* {@code obj.toString()} is returned.
* @see java.lang.Object#toString()
*/
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
So you can see that the toString()
is called for you.
As this is in the documentation, you can assume this won't change in the future or in another implementation. ie the code might change but the documented functionality will always be preserved.
System.out.println(test);
在test
将在此处调用toString()
来打印输出。
当您打印出对象时,就像在最后一行中所做的那样,该对象将使用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.