java toString Questions

Asked 2 years ago, Updated 2 years ago, 32 views

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

2022-09-30 20:49

2 Answers

First, System.out is the field that holds the standard output stream for the System class.
It is an instance of PrintStream and calls println(Object x).
PrintStream #println as described in 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 (println) calls String.valueOf(x).

A string equal to ulnull " if the argument is null.Otherwise, obj.toString() value is returned.

Consequently, obj.toString() is called in String.valueOf, so the expected behavior (overrided toString method is called).That's right.


2022-09-30 20:49

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().


2022-09-30 20:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.