Reputation: 3415
Object aThing = new Integer(25);
aThing.toString();
Is it the toString
of the Object
or toString
of the Integer
? (I think it's Integer
's.)
Upvotes: 1
Views: 116
Reputation: 66657
Integer
class toString()
will be called. Method invocation will always be decided based on the Object type rather than reference type.
As Steve Kuo commented: except static methods.
Upvotes: 3
Reputation: 14257
Integer's
toString
is called. Which method implementation is called is always determined by the runtime type (class) of the object itself, not by the type of the variable it is assigned to. In the following code, both of the calls are equivalent.
Integer i = Integer.valueOf(5);
Object o = i;
i.toString(); // "5"
o.toString(); // "5"
Methods that behave this way are called Virtual Methods. All non-static methods in Java are virtual. They provide one of key mechanisms of Polymorphism.
Upvotes: 1
Reputation: 15641
The toString()
of the Integer
, is the one that is called.
You can easily prove that with an object of your own.
Upvotes: 1
Reputation: 2639
toString()
in the integer class is executed since it's the type of the instantiated class.
Upvotes: 1