interface运算类,加法类,减法类,乘法类,除法类
时间: 2024-06-03 22:05:01 浏览: 87
objc代码-两数加减乘除,类方法
interface是Java语言中的关键字,用于定义接口。接口是一种约定,它规定了一个类应该具有哪些方法,但不涉及方法的具体实现。在接口中定义的方法必须被实现,否则会导致编译错误。
加法类、减法类、乘法类、除法类是四个基本的运算类,它们分别实现了不同的数学运算。这些类可以实现一个接口,例如MathOperation接口,该接口定义了一组抽象方法,如add()、subtract()、multiply()、divide()等,这些方法分别对应四种运算。这样就可以使用多态来调用这些运算类的方法,使代码更加简洁和可维护。
下面是一个示例代码:
```
public interface MathOperation {
public double add(double a, double b);
public double subtract(double a, double b);
public double multiply(double a, double b);
public double divide(double a, double b);
}
public class Addition implements MathOperation {
public double add(double a, double b) {
return a + b;
}
public double subtract(double a, double b) {
return 0;
}
public double multiply(double a, double b) {
return 0;
}
public double divide(double a, double b) {
return 0;
}
}
public class Subtraction implements MathOperation {
public double add(double a, double b) {
return 0;
}
public double subtract(double a, double b) {
return a - b;
}
public double multiply(double a, double b) {
return 0;
}
public double divide(double a, double b) {
return 0;
}
}
public class Multiplication implements MathOperation {
public double add(double a, double b) {
return 0;
}
public double subtract(double a, double b) {
return 0;
}
public double multiply(double a, double b) {
return a * b;
}
public double divide(double a, double b) {
return 0;
}
}
public class Division implements MathOperation {
public double add(double a, double b) {
return 0;
}
public double subtract(double a, double b) {
return 0;
}
public double multiply(double a, double b) {
return 0;
}
public double divide(double a, double b) {
if(b != 0) {
return a / b;
} else {
throw new IllegalArgumentException("Divisor cannot be zero!");
}
}
}
```
阅读全文