tostring()重写的工作原理

bxgwgixi  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(486)

我刚刚知道 toString() 方法以及如何在其他类中重写它。

class Box {
      public String toString(){
          return "class Box";
      }
}

class B {
    public static void main(String args[]){
        Box b1=new Box();
        System.out.println(b1); //case 1
        Box b2=b1; //case 2
    }
}

所以我的问题是box对象如何知道在 toString() 在案例1的类框中,返回 b1 案例2中的对象地址?

roqulrg3

roqulrg31#

这个 System.out.println 您调用的方法是 (Object) 超载,不是吗 (String) . PrintStream.println(Object) 电话 toString() 关于它的论点(迂腐:直接或间接,除非论点是 null ).

nwo49xxi

nwo49xxi2#

没有魔法。如果你深入研究这个方法,最终 toString 显式调用。

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString(); //in your case obj = the box in b1
}

相关问题