bound types
Fri Jun 07 2024 11:55:13 GMT+0000 (Coordinated Universal Time)
Saved by
@dbms
public class BoundedArithmetic<T extends Number> {
public double add(T a, T b) {
return a.doubleValue() + b.doubleValue();
}
public double subtract(T a, T b) {
return a.doubleValue() - b.doubleValue();
}
public double multiply(T a, T b) {
return a.doubleValue() * b.doubleValue();
}
public double divide(T a, T b) {
if (b.doubleValue() == 0) {
throw new ArithmeticException("Division by zero is not allowed.");
}
return a.doubleValue() / b.doubleValue();
}
public static void main(String[] args) {
BoundedArithmetic<Number> calculator = new BoundedArithmetic<>();
Integer a = 10;
Integer b = 5;
System.out.println("Addition: " + calculator.add(a, b));
System.out.println("Subtraction: " + calculator.subtract(a, b));
System.out.println("Multiplication: " + calculator.multiply(a, b));
System.out.println("Division: " + calculator.divide(a, b));
Double x = 15.5;
Double y = 4.5;
System.out.println("Addition (Double): " + calculator.add(x, y));
System.out.println("Subtraction (Double): " + calculator.subtract(x, y));
System.out.println("Multiplication (Double): " + calculator.multiply(x, y));
System.out.println("Division (Double): " + calculator.divide(x, y));
}
}
content_copyCOPY
Comments