Tuesday, July 23, 2024

Addition and Subtraction Using Polymorphism in Java

 


Program Listing

import java.util.Scanner;


class MathOperation {

    public int performOperation(int a, int b) {

        return 0; // Base class default implementation

    }

}


class Addition extends MathOperation {

    @Override

    public int performOperation(int a, int b) {

        return a + b;

    }

}


class Subtraction extends MathOperation {

    @Override

    public int performOperation(int a, int b) {

        return a - b;

    }

}


public class Main {

    public static void main(String[] args) {

        MathOperation operation = null;

        int num1, num2;

        char op;


        Scanner scanner = new Scanner(System.in);


        System.out.println("\n\n\tAddition and Subtraction Using Polymorphism in Java\n");

        System.out.print("\tEnter two numbers: ");

        num1 = scanner.nextInt();

        num2 = scanner.nextInt();

        System.out.print("\tEnter the operation (+ for addition, - for subtraction): ");

        op = scanner.next().charAt(0);


        if (op == '+') {

            operation = new Addition();

        } else if (op == '-') {

            operation = new Subtraction();

        } else {

            System.out.println("\tInvalid operation.");

            return;

        }


        int result = operation.performOperation(num1, num2);

        System.out.println("\n\tThe Result: " + result);


        scanner.close();


        System.out.println("\n\tEnd of Program. Thank you for using this program.");

    }

}


No comments:

Post a Comment