Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call toString() when convert String to Object [duplicate]

Tags:

java

Here is my example code:

String str = "hello";
Object obj = (Object)str;
System.out.println(obj.toString());

I found the source code of Object, and the toString() method is:

public String toString() {   
   return getClass().getName() + "@" + Integer.toHexString(hashCode());
} 

I thought the result of the example shound be the address of this Object, like [B@15db9742 , after I convert str to Object , but it still print hello. Why? Shoundn't obj use the method of Object? Can Anyone explain the principle of it to me?

like image 945
Chestnut Avatar asked Feb 06 '26 00:02

Chestnut


1 Answers

This is polymorphism (specifically, runtime polymorphism). It doesn't matter what the type of your reference to the object is (Object or String), as long as that type has toString (so your code compiles), the toString that will be used is the one the object itself actually has, not necessarily the one provided by the type of your reference. In this case, the object is a String no matter what the type of your reference to it is, so String#toString is used.

like image 79
3 revs, 2 users 58%T.J. Crowder Avatar answered Feb 08 '26 14:02

3 revs, 2 users 58%T.J. Crowder