print和println默认调用类中的public String toString(){return "***"} 分析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pmcasp/article/details/83004997

先看下来自mindview的一段代码:

 
  1. package reusing;

  2.  
  3. //: reusing/Bath.java

  4. // Constructor initialization with composition.

  5. import static net.mindview.util.Print.*;

  6.  
  7. class Soap {

  8. private String s;

  9.  
  10. Soap() {

  11. print("Soap()");

  12. s = "Constructed";

  13. }

  14.  
  15. public String toString() {

  16. return s;

  17. }

  18. }

  19.  
  20. public class Bath {

  21. private String // Initializing at point of definition:

  22. s1 = "Happy",

  23. s2 = "Happy", s3, s4;

  24. private Soap castille;

  25. private int i;

  26. private float toy;

  27.  
  28. public Bath() {

  29. print("Inside Bath()");

  30. s3 = "Joy";

  31. toy = 3.14f;

  32. castille = new Soap();

  33. }

  34.  
  35. // Instance initialization:

  36. {

  37. i = 47;

  38. }

  39.  
  40. public String toString() {

  41. if (s4 == null) // Delayed initialization:

  42. s4 = "Joy";

  43. return "s1 = " + s1 + "\n" + "s2 = " + s2 + "\n" + "s3 = " + s3 + "\n"

  44. + "s4 = " + s4 + "\n" + "i = " + i + "\n" + "toy = " + toy

  45. + "\n" + "castille = " + castille;

  46. }

  47.  
  48. public static void main(String[] args) {

  49. Bath b = new Bath();

  50. print(b);

  51. }

  52. }

打印对象b的时候,构造函数内的自动会调用初始化,还自动调用了toString()

为什么toString 方法会自动被调用?

这个问题其实比较简单的,大家可以直接看 Java 中相关类的源代码就可以知道了。

public static String valueOf(Object obj) 方法
参数: obj 

返回:

       如果参数为 null, 则字符串等于 "null";

       否则, 返回 obj.toString() 的值

现在的问题是,当用户调用 print 或 println 方法打印一个对象时,为什么会打印出对象的 toString()方法的返回信息。public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }

1.这个是 Ojbect 中的 toString()方法,toString ()方法会打印出 return 信息。
  public void println(Object x){
             String s = String.valueOf(x);
             synchronized (this) { 
                      print(s); newLine();
      }
   public void print(Object obj) {
              write(String.valueOf(obj));
  }
2.这两个方法是 System.out.print 和 println()方法传入一个 Object 类对象时打印 的内容,当然,传入其它类时,同样如此。 

3.我们看到,在 2 中,当要打印一个对象时,会自动调用 String.valueOf()这个 方法,下面是这个方法的代码: 

 
  1. public static String valueOf(Object obj) {

  2. return (obj == null) ? "null" : obj.toString();

  3. }

这个方法中,当传入的对象为 null 时返回一个 null,当非 null 时,则返回这个 obj 的 toString()。
所以, 这就是当我们调用 print 或者 println 打印一个对象时,它会打印出这个 对象的 toString()的最终根源。

--------------------- 作者:anddyhua 来源:CSDN 原文:https://blog.csdn.net/anddyhua/article/details/42675099?utm_source=copy 版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/pmcasp/article/details/83004997
今日推荐