为什么在打印对象时调用toString()方法?

Nic*_*ong 8 java object

我似乎无法理解为什么当我在quarter对象上使用println方法时,它返回toString方法的值.我从来没有调用过toString方法为什么我得到返回值?

public class Main {
    public static void main(String[] args) {
        Quarter q = new Quarter();
        Nickel n = new Nickel();
        System.out.println(q);
        System.out.println(n);
    }
}

public abstract class Money {
    private int value;

    public Money(int v) {
        value=v;
    }

    public abstract int getValue();

    protected int myValue() {
        return value;
    }

    public abstract String toString();
}

public abstract class Coin extends Money {
    public Coin(int value) {
        super(value);
        System.out.println("I am a coin, my value is " + getValue());
    }
}

public class Quarter extends Coin {
    public Quarter () {
        super(25);
    }

    public int getValue() {
        return myValue();
    }

    public String toString() {
        return "A Quarter is "+getValue();
    }
}

public class Nickel extends Coin {
    public Nickel () {
        super(5);
    }

    public int getValue() {
        return myValue();
    }

    public String toString() {
        return "A "+this.getClass().getName()+ " is "+getValue();
    }
}
Run Code Online (Sandbox Code Playgroud)

Pra*_*eek 18

在参考java文档我不知道的是,

当你调用PrintStream类print(obj)/ println(obj)方法然后在内部调用write方法时,arguement为String.valueOf(obj),如下所示:

public void print(Object obj) {
    write(String.valueOf(obj));
}
Run Code Online (Sandbox Code Playgroud)

现在String.valueOf(obj)执行调用String方法的任务,如下所示:

 /**
 * Returns the string representation of the <code>Object</code> argument.
 *
 * @param   obj   an <code>Object</code>.
 * @return  if the argument is <code>null</code>, then a string equal to
 *          <code>"null"</code>; otherwise, the value of
 *          <code>obj.toString()</code> 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)


Oli*_*rth 3

因为PrintStream.println有一个重载,它接受一个Object, 然后调用它的toString方法。