Mike Mike - 5 months ago 14
Java Question

Reusing same function in different ways

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.

Answer

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 max
obj1.operation(a,b) // calculates min