利用Debug
自动调用toString方法

public class Le{
 public static void main(String[] args) {
  Le kk=new Le();
  System.out.println(kk);
  }
}
所有的类都是继承自Object类,自然继承了toString方法,在当使用

System,out.println()里面为一个对象的引用时,自动调用toString方法把对象

打印出来。如果重写了tostring方法则调用重写的toString 方法。

因为System.out.println()的这个方法源码中调用了String.valueOf(Objec o),
public void println(Object x) {
        String s = String.valueOf(x);
        synchronized (this) {
            print(s);
            newLine();
        }
    }
而String.valueOf(x)方法的源码就是去调用该对象的toString()方法。
public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }





相关文章:

  • 2021-11-22
  • 2022-12-23
  • 2021-10-11
  • 2022-12-23
  • 2021-07-11
  • 2021-08-01
  • 2021-08-27
猜你喜欢
  • 2021-10-01
  • 2021-10-23
  • 2021-09-23
  • 2021-09-10
  • 2021-09-17
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案