Ah=newA();
h.name = "Aye";
System.out.println(h.toString());
The book says that the h.toString()
section above can only be h
, but why does the h
call the toString
method overridden in class A?
Is that the rule?
Please let me know if you know more.Thank you for your cooperation.
java
First, System.out is the field that holds the standard output stream for the Print an Object to exit the line.This method first calls String.valueOf(x) to get the string value of the object that is output.Then it works the same way as calling print(String) and then println(). So this ( A string equal to ulnull " if the argument is null.Otherwise, obj.toString() value is returned. Consequently, System
class.
It is an instance of PrintStream
and calls println(Object x).
PrintStream #println as described in the println
) calls String.valueOf(x).obj.toString()
is called in String.valueOf
, so the expected behavior (overrided toString method is called).That's right.
Java refers to toString
when an instance of an object is stringed.
class A {
private String name = "I'm A";
}
classB{
private String name = "I'm B";
public String to String() {
return name;
}
}
public class Foo{
public static void main(String[]args) {
System.out.println(newA()); // Object.toString() is called
System.out.println(newB()); // B toString() is called
Same as System.out.println("Yes, "+newB())); // "Yes, "+(newB()) .toString()
}
}
The first and second are understood, but the third is actually the same as "Yes,"+(new B()) .toString()
.
© 2024 OneMinuteCode. All rights reserved.