What’s the return value of an instance?Will the String method be executed during the process of creating an instance? | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 1

What’s the return value of an instance?Will the String method be executed during the process of creating an instance?

Why the output Is x? class A{ int x; public A(int y) { x=y; } public String toString() { return “x”; } } public class B{ public static void main(String[] args){ System.out.print(new A(10)); } }

26th Feb 2019, 9:03 AM
Dane.L
Dane.L - avatar
2 Réponses
+ 8
It's the object itself, Java tries to auto-typecast it to string by using its builtin toString (probably...)
26th Feb 2019, 9:05 AM
Valen.H. ~
Valen.H. ~ - avatar
0
I read an article occasionally and found that the point is the source code of toString method,when you print sth,it will call valueOf method and the valueOf will call toString method.Then class A overrides toString method,so it return “x”.
27th Feb 2019, 12:20 PM
Dane.L
Dane.L - avatar