为什么在打印对象时调用 toString() 方法? [英] Why is the toString() method being called when I print an object?

查看:31
本文介绍了为什么在打印对象时调用 toString() 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can't seem to understand why when I use println method on the quarter object, it returns the value of the toString method. I never called the toString method why am I getting the return value?

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();
    }
}

推荐答案

关于 Java 文档,我不明白的是,

On Refering to java docs what i undestand is that,

当您调用 PrintStream 类 print(obj)/println(obj) 方法时,它在内部调用 write 方法,参数为 String.valueOf(obj)如下图:

When you call PrintStream class print(obj) / println(obj) method then internally it called write method with arguement as String.valueOf(obj) shown below :

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

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

Now String.valueOf(obj) does the task of calling to String method as shown below :

 /**
 * 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();
}

这篇关于为什么在打印对象时调用 toString() 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆