[Solved] Overload a toString Method


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

2

solved Overload a toString Method