Calling toString () when converting String to Object

Here's my sample code:

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

      

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

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

      

I thought the result of the example is the address of that object, like [B @ 15db9742, after converting str to Object, but it still prints hello. What for? Don't use Object method? Can anyone explain the principle of this to me?

+3


source to share


4 answers


This is polymorphism (in particular, runtime polymorphism). It doesn't matter what the type of your object reference is ( Object

or String

), if that type is toString

(which is why your code is compiled) toString

, what will be used will be the one that the object itself actually has, not the one provided by the type of your reference ... In this case, the object is String

regardless of the type of reference to it, therefore it is used String#toString

.



+5


source


Because the underlying object is a String object, and the String class overrides the toString()

.

Although you have an Object type on the left, methods from the implemented class are executed, and a common phenomenon is called polymorphism. You just change the shape of the string to an object.

When you do



Object obj = (Object)str;

      

This does not change String to Object class. You are just changing the type of the object, not its actual behavior.

+2


source


Calling a virtual method implies that the method will be overridden based on the actual implementation, as opposed to the implementation on a reference type.

In other words, your instance String

will still invoke method overrides Object

implemented in String

, even if you distinguish them as Object

.

+1


source


The obj object is the result of (unnecessary) translation, but is still a string .... the String class has a toString method implemented :

public String toString() {
    return this;
}

      

check that obj is a string by running:

System.out.println(str.getClass());
System.out.println(obj.getClass());

      

You'll get

java.lang.String class

java.lang.String class

0


source







All Articles