为什么我得到这个输出,但不要使用String

KaZ*_*yKa -1 java tostring output

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

所以在我的输出中我打印了一个俱乐部.但我没有使用toString()我只是从我的构造函数中定义一个新的卡.那么有人可以向我解释为什么我得到这个输出?

Pet*_*rey 9

如果你看看你看到的PrintWriter.println(Object)的Javadoc和源代码

/**
 * 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

反过来,String.valueOf(Object)可以

/**
 * 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();
}
Run Code Online (Sandbox Code Playgroud)

所以你可以看到toString()为你而来.

正如文档中所述,您可以假设将来或其他实现中不会更改.即代码可能会更改,但记录的功能将始终保留.