Posts

Search

The Adder Class

There are different kinds of calculators which are available in the market for different purposes. Sam wants to make a calculator which can return the sum of two integers.

Implement the Adder class which should follow the following:

It should inherit from the Calculator class .
It should implement the method add(int a, int b) which should calculate and return the sum of two integer parameters, a and b.
 

The locked stub code in the editor consists of the following:

An abstract class named Calculator which contains an abstract method, add(int a, int b).
A solution class which
creates an object of the Adder class. 
reads the inputs and passes them in a method called by the object of the Adder class.
 

Constraints

0 < a, b < 105
Input Format For Custom Testing
The only line contains two space-separated integers, a and b.

Sample Case 0
Sample Input For Custom Testing

1 1
Sample Output

The sum is: 2
Explanation

When the add method is called with the arguments a = 1 and b = 1, it calculates and returns their sum as 1 + 1 = 2, which is then printed.

Sample Case 1
Sample Input For Custom Testing

2 3
Sample Output

5
Explanation

When the add method is called with the arguments a = 2 and b = 3, it calculates and returns their sum as 2 + 3 = 5, which is then printed.

SOLUTION :

import java.util.Scanner;

abstract class Calculator {
    abstract int add(int a, int b);
}
/*
 Write the Adder class here. Do not use an access modifier at the beginning of your class declaration.
 */
class Adder extends Calculator
{
    int add(int a,int b)
    {
        return (a+b);
    }
}
public class Solution {
    public static void main(String[] args) {
        int a, b;
        try (Scanner scan = new Scanner(System.in)) {
            a = scan.nextInt();
            b = scan.nextInt();
        }

        Calculator adderObject = new Adder();
        System.out.println("The sum is: " + adderObject.add(a, b));
    }
}