Navleen Singh
Navleen Singh

Reputation: 155

Method overloading toString()

Hi I was just wondering if it is possible to have multiple toString() methods in the same class. The two different toString() methods print different things. ex:

public String toString(){
    return String.format("(%.1f%+.1fi)%n", real, imaginary);
}

public String toString(){
    return String.format("z=%.3f(cos(%.3f)+isin(%.3f))%n",real,imaginary,imaginary);
} 

Upvotes: 1

Views: 5457

Answers (3)

SHIV
SHIV

Reputation: 21

No, it is not possible to overrides multiple toString() in the same Class

Upvotes: 0

Syed Mauze Rehan
Syed Mauze Rehan

Reputation: 1145

You can have a toString() method that takes an argument to indicate the expected format of the output. Say you have 3 formats. You can have an enum and based on the value you get, you print/return the value in that format.

EDIT 1

Let's say you have an enum

public enum PrintFormat{
    F1, F2, F3
}

and the toString() method that you're going to overload

public toString(PrintFormat format){
    switch(format){
        case F1:
           //return in a diff format
        case F2:
           //return in a diff format
        //so on so forth
    }
}

Upvotes: 1

markspace
markspace

Reputation: 11030

No, you can't have two methods with the same name and signature.

A "signature" in this case means the number of arguments and their types. Changing this won't allow you to override toString() twice, it'll just make one a normal method.

public String toString(){
    return String.format("(%.1f%+.1fi)%n", real, imaginary);
}

public String toString( boolean fubar ){
    return String.format("z=%.3f(cos(%.3f)+isin(%.3f))%n",real,imaginary,imaginary);
} 

The second method has a different signature, so it's legal, but doesn't override toString().

Upvotes: 4

Related Questions