Skip to content
Advertisement

How to override toString() properly in Java?

Sounds a little stupid, but I need help on my toString() method and it is very irking. I tried looking up online because the toString is the one where it is screwing up and “not finding Kid constructor #2” even though it is there and I would even do something else and it doesn’t work. Ok that was a lot so here is my code:

import java.util.*; 
   class Kid {  
      String name; 
      double height; 
      GregorianCalendar bDay; 

      public Kid () { 
         this.name = "HEAD";
         this.height = 1; 
         this.bDay = new GregorianCalendar(1111,1,1); 
      } 

      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;
      } 

      public String toString() { 
         return Kid(this.name, this.height, this.bDay);
      } 
   } //end class 

Ok So my toString above (I know, my third parameter is off, should be a String) is off. If I hardcode a value in for the third thing it goes haywire and says it can’t find this (up above). So how can I get the date and break it up?

Class calling this is below

class Driver {   
   public static void main (String[] args) {   
      Kid kid1 = new Kid("Lexie", 2.6, "11/5/2009");   
      System.out.println(kid1.toString());
   } //end main method 
} //end class  

I tried researching multiple constructors and it really didn’t help. I tried researching toString() methods, and tried using previous toString() methods logic that I created previous but this is brand new so it never worked.

Help?

Advertisement

Answer

The toString is supposed to return a String.

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

I suggest you make use of your IDE’s features to generate the toString method. Don’t hand-code it.

For instance, Eclipse can do so if you simply right-click on the source code and select Source > Generate toString

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement