对象如何隐式调用toString方法? [英] How an object will call toString method implicitly?

查看:380
本文介绍了对象如何隐式调用toString方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我正在打印该类的对象,那么即使我没有编写 toString(),它也会打印 toString()方法实现方法那么实现是什么,如何在内部调用 toString()

If I am printing an object of the class then it is printing the toString() method implementation even I am not writing the toString() method so what are the implementation,how it is calling toString() internally?

推荐答案

你没有明确地调用 toString(),但是你有以下意思:

You're not explicitly calling toString(), but impliclty you are:

参见:

System.out.println(foo); // foo is a non primitive variable

系统 是一个类, static 字段 out ,类型 PrintStream 。所以你要调用 println(Object) PrintStream的方法

它实现如下:

   public void println(Object x) {
       String s = String.valueOf(x);
       synchronized (this) {
           print(s);
           newLine();
       }
   }

如我们所见,它正在调用 String .valueOf(Object) 方法。这实现如下:

As wee see, it's calling the String.valueOf(Object) method. This is implemented as follows:

   public static String valueOf(Object obj) {
       return (obj == null) ? "null" : obj.toString();
   }

在这里你看, toString() 被调用。

And here you see, that toString() is called.

这篇关于对象如何隐式调用toString方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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