Slim Shady Slim Shady - 2 months ago 21
Java Question

Overload a toString Method

I'm trying to write a toString method for a class with multiple constructors:

public Fraction(int n1, int d1, int n2, int d2)
{
num1=n1;
den1=d1;
num2=n2;
den2=d2;
}


and

public Fraction(int nAns, int dAns)
{
nAnswer=nAns;
dAnswer=dAns;
}


However, when I try to write a toString, I keep getting compilation errors when I do (probably because both methods are called toString):

public String toString()
{
return "Fraction[numerator1="+num1+", numerator2="+num2+", denominator1="+den1+", denominator2="+den2+"]";
}

public String toString()
{
return "Fraction[nAnswer="+nAnswer+", dAnswer="+dAnswer+"]";
}


If I name one of the toString methods toString and the other one toString2, the program compiles but doesn't give me the desired output for toString2.

So I then tried writing an if statement for this method, but I'm not sure how I would write the if part (how do I say "If your fraction looks like the first constructor, return the first toString; if your fraction looks like the second constructor, return the second toString"?).

I tried the following, but I know that the if part is wrong because I keep getting compilation errors:

if Fraction==Fraction(int num1, int den1, int num1, int den2)
{
public String toString()
{
return "Fraction[numerator1="+num1+", numerator2="+num2+", denominator1="+den1+", denominator2="+den2+"]";
}
else if Fraction==Fraction(int nAnswer, int dAnswer)
{
public String toString()
{
return "Fraction[nAnswer="+nAnswer+", dAnswer="+dAnswer+"]";
}
}


But I know that an overloaded toString method is possible because so many classes in the Java library use it (for example, the Rectangle class).

Any suggestions? Thanks in advance!

Answer

First of all, toString method comes from object class, don't try to make multiple of those methods or anything like that, have everything in one method. As to your problem, you can make a variable String description for your class, and initialize it in constructor and then in toString just return that variable. You can do that if you are not changing your object any other way after creating them, but that's probably not the case. You can also make two boolean variables createdByFirstConstructor and createdBySecondConstructor and initialize them with false. Then in both constructors change corrseponding variable to true and then in toString just check which variable is set to true and print accordingly. Hope this helps. There is probably easier solution, but it's not coming to my mind right now, maybe later.

private boolean createdByFirst = false;
private boolean createdBySecond = false;

public Fraction(yourCode){
  createdByFirst = true;
}

public Fraction(yourOtherCode){
  createdBySecond = true;
}

public String toString(){
  if(createdByFirst)
    return "yourStringForFirstConstructor";
  else if(createdBySecond)
    return "yourStringForSecondConstructor";
  else
    return "Something else";
}