Home >Java >javaTutorial >How to Correctly Implement and Call the toString() Method in Java?

How to Correctly Implement and Call the toString() Method in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-30 20:00:18487browse

How to Correctly Implement and Call the toString() Method in Java?

Addressing toString() Implementation in Java

In Java, the toString() method allows you to define a custom representation of an object as a string. Its default implementation provides class and identity information, but it can be overridden for a tailored output.

Proper toString() Override

Your Kid class attempts to use a constructor in the toString() method, which is incorrect. toString() should return a string representation, not create a new object.

To fix your code, return a string containing the object's data. For example:

public String toString() {
    return "Name: '" + this.name + "', Height: '" + this.height + "', Birthday: '" + this.bDay + "'";
}

Alternatively, you can use your IDE's code generation features to automatically create a toString() method. For instance, in Eclipse, right-click on the code and select Source > Generate toString.

Troubleshooting Constructor Call

The constructor in your Kid class has the wrong syntax:

public Kid (String n, double h, String date) {
      // method that toString() can't find somehow
      StringTokenizer st = new StringTokenizer(date, "/", true);
      n = this.name;
      h = this.height;
   }

The correct syntax for a constructor is:

public Kid (String name, double height, String date) {
    this.name = name;
    this.height = height;
    // Parse date here
}

Calling toString()

The code in your Driver class correctly calls the toString() method on kid1 and prints its result:

System.out.println(kid1.toString());

This will output the customized string representation of the Kid object, as specified in the toString() method.

The above is the detailed content of How to Correctly Implement and Call the toString() Method in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn