1.3-Object-Georienteerd-Programmeren

Calculations

In this assignment we are going to practice with abstract classes and abstract methods. We want you to create classes for different types of calculations, such as summing, subtracting, etc. The superclass we need is called Calculation. This class is created with two numbers (value1 and value2) for which of course you use the constructor. The class also has an abstract method double calculate() which needs to be implemented in the subclasses.

There are four classes that inherit from the Calculation class:

Example

The following code …

public static void main(String[] args) {
    ArrayList<Calculation> calculations = new ArrayList<>();

    // Add a bunch of calculations
    calculations.add(new SumCalculation(5, 10));
    calculations.add(new SubtractCalculation(20, 10));
    calculations.add(new MultiplyCalculation(20, 6));
    calculations.add(new DivisionCalculation(35, 7));

    try {
        calculations.add(new DivisionCalculation(35, 0));
    } catch (IllegalStateException ise) {
        System.err.println("Error: " + ise.getMessage());
    }

    // Execute calculations
    for (Calculation calculation : calculations) {
        System.out.println(calculation);
    }
}

… produces the following output:

Error: Cannot divide by 0.
5.0 + 10.0 = 15.0
20.0 - 10.0 = 10.0
20.0 * 6.0 = 120.0
35.0 / 7.0 = 5.0

Please note that the last division (35 / 0) is illegal as it is not allowed to divide any number by 0. In our solution, we have opted to have the constructor check the value immediately.