user133466
user133466

Reputation: 3415

which .toString is called in this case?

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

Answers (5)

kosa
kosa

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

Natix
Natix

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

Frank
Frank

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

Tulains Córdova
Tulains Córdova

Reputation: 2639

toString() in the integer class is executed since it's the type of the instantiated class.

Upvotes: 1

Dan D.
Dan D.

Reputation: 32391

The one on the subclass is called, so the one on the Integer.

Upvotes: 1

Related Questions