EvG
EvG

Reputation: 65

Change sign + for a String that does the same action (like Operator overloading)

There are 2 variables and I need to sum them. But instead using the + sign I'd like to change it for a String.

double var1 = 1;
double var2 = 2;
String sign = "+"; 

double variable3 = var1 sign var2;

I'd like to sum them using the "sign" instead, But i don't know if there's a way to do this.

Upvotes: 0

Views: 39

Answers (2)

user2342558
user2342558

Reputation: 6693

Java doesn't allow "Operator overloading", see this SO post for some info.

But, you can use a method to handle the sign like this:

double handleOperation(String sign, double int1, double int2)
{
    if(sign.equals("+")) {
        return int1 + int2;
    }
    else if(sign.equals("-")) {
        return int1 - int2;
    }
    // others

    return 0;
}

double var1 = 1;
double var2 = 2;
String sign = "+"; 

double variable3 = handleOperation(sign, var1, var2);

Upvotes: 1

DzianisH
DzianisH

Reputation: 95

In Java you can't override operators like in C++. You can override only methods.

Upvotes: 1

Related Questions