1

I just learnt about the toString() method in object class and how to override it in other class.

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
    }
}

So my question is how does box object know to return the String in the toString() in class Box in case 1 and return the b1 object's address in case 2?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
R. S. D
  • 33
  • 4

2 Answers2

3

The System.out.println method you are calling is the (Object) overload, not (String). PrintStream.println(Object) calls toString() on its argument (pedantry: directly or indirectly, unless the argument is null).

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
2

There is no magic. If you dig down into the method, eventually toString is called explicitly.

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString(); //in your case obj = the box in b1
}
Michael
  • 41,989
  • 11
  • 82
  • 128