Hello, I am new to the forum and to Java. Almost finished the Intro to Java course.
The only part so far I am unsure of is about toString().
Please see my example here I am using…
How does toString() know which object with which it is to return for since its outside the constructor? there is no reference inside the toString() method to say which object to work on. Just curious how that works. As a test I put the toString() inside the constructor and got an error.
Is it really needed? I mean its just saving the part of doing the syso in the main as opposed to returning the value stored. Is it really saving that much code for what it’s worth here?
The toString() method in Java is inherited from the Object class and is used to provide a string representation of an object. When called, it returns a default string containing the class name and hashcode. Overriding toString() in a class allows for a custom, more meaningful representation of the object. This is valuable for debugging and logging purposes. Placing toString() inside the constructor is not standard practice and can lead to unexpected behavior. The method is not about saving code but rather providing a standardized way to represent objects as strings.