Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing same function in different ways

Tags:

java

I have got class like this

class Calculate {
    int operation(int a, int b){
         return Math.max(a,b);
    }
    int calc(int a, int b){
        int x=100+a*b;
        int y=a+a*b;
        retun operation(x,y);
    }
    int calc1(int a, int b){
        int x=100+a*b;
        int y=b+a*b;
        return operation(x,y);
    }
}

Now I make two objects of this class as
Calculate obj1=new Calculate();
Calculate obj2=new Calculate();
I want function operation of Class calculate to act like returning maximum of two values for obj1, and return minimum of two values for obj2. Can this be done?
I could only think of creation two different classes Calculate1 and Calculate2 and defining operation as maximum in Calculate1 and minimum in Calculate2 and defining rest thing as same as it is. I hope some easier method also exist without defining two classes.

like image 389
Mike Avatar asked May 18 '26 09:05

Mike


2 Answers

You can pass the operation to the constructor as an IntBinaryOperator, for example:

class Calculate {

  private final IntBinaryOperator op;

  public Calculate(IntBinaryOperator operator) {
    this.op = operator;
  }

  int operation(int a, int b) {
    return op.applyAsInt(a, b);
  }
}

Now you can write:

Calculate c1 = new Calculate(Math::max);
Calculate c2 = new Calculate(Math::min);

And adding an operation is easy - say you want the sum instead of min or max:

Calculate c3 = new Calculate((x, y) -> x + y);
like image 97
assylias Avatar answered May 20 '26 22:05

assylias


You can override the operation method.

If you don't want to create explicit sub-classes, you can do this with anonymous classes :

Calculate obj1=new Calculate();
Calculate obj2=new Calculate() {
    int operation(int a, int b){
        return Math.min(a,b);
    }
};

obj1.operation(a,b) // calculates maximum
obj2.operation(a,b) // calculates minimum
like image 26
Eran Avatar answered May 20 '26 23:05

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!