How to save the previous result

bhxbr922 :

I have a task

Create a class Math with methods: int calculate (int a, int b) - the operation itself and int returnPrev () - returns the previous calculated result.

Create class Addition to represent addition operations. Override the methods. I've created abstract class Math

    abstract class Math {
        abstract int calculate(int a,int b);
        abstract int returnPrev();
    }


    public class Addition extends Math {
        int result;
        int prevresult;


        @Override
        int calculate(int a, int b) {
           result = a + b;
            return result   }
        @Override
        int returnPrevious() {
         }
    }

For me is unclear how should i create a method returnPrevious ?? I do not understand how should i save the first result.

For any explanation would be very grateful

Arvind Kumar Avinash :
  1. Do not use a name which OOTB e.g you should use MyMath to avoid conflict with OOTB Math.
  2. It's better to declare MyMath as in interface. Note that multiple interfaces can be implemented by a class but only one class can be extended.
  3. Assign the value of result to prevresult before putting the value of new calculation into it.

interface MyMath {
    public int calculate(int a, int b);
    public int returnPrev();
}

class Addition implements MyMath {
    int result;
    int prevresult;

    @Override
    public int calculate(int a, int b) {
        prevresult = result;
        result = a + b;
        return result;
    }

    @Override
    public int returnPrev() {
        return prevresult;
    }
}

public class Demo {

    public static void main(String[] args) {
        Addition addition = new Addition();
        System.out.println(addition.calculate(10, 20));
        System.out.println(addition.returnPrev());
        System.out.println(addition.calculate(20, 30));
        System.out.println(addition.returnPrev());
    }
}

Output:

30
0
50
30

Feel free to comment in case of any doubt/issue.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=409779&siteId=1