Learn Computer Programming Free from our source codes in my website.
Sponsored Link Please Support
https://www.techseries.dev/a/27966/qWm8FwLb
https://www.techseries.dev/a/19181/qWm8FwLb
My Personal Website is http://www.jakerpomperada.com
Email me at jakerpomperada@gmail.com and jakerpomperada@yahoo.com
Saturday, July 27, 2024
Friday, July 26, 2024
Thursday, July 25, 2024
Wednesday, July 24, 2024
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.");
}
}