以下是一个示例代码,演示了如何在同一个类的两个实例上执行算术运算:
public class ArithmeticOperation {
private int number;
public ArithmeticOperation(int number) {
this.number = number;
}
public int add(ArithmeticOperation other) {
return this.number + other.number;
}
public int subtract(ArithmeticOperation other) {
return this.number - other.number;
}
public int multiply(ArithmeticOperation other) {
return this.number * other.number;
}
public int divide(ArithmeticOperation other) {
if (other.number != 0) {
return this.number / other.number;
} else {
throw new IllegalArgumentException("除数不能为零");
}
}
public static void main(String[] args) {
ArithmeticOperation a = new ArithmeticOperation(5);
ArithmeticOperation b = new ArithmeticOperation(3);
int sum = a.add(b);
int difference = a.subtract(b);
int product = a.multiply(b);
int quotient = a.divide(b);
System.out.println("和:" + sum);
System.out.println("差:" + difference);
System.out.println("积:" + product);
System.out.println("商:" + quotient);
}
}
在上述代码中,ArithmeticOperation
类表示一个包含一个整数属性的类。它包含了add
、subtract
、multiply
和divide
方法,用于执行加法、减法、乘法和除法运算。在main
方法中,我们创建了两个ArithmeticOperation
类的实例a
和b
,然后使用这些实例执行算术运算,并将结果打印到控制台上。
运行上述代码,输出结果将是:
和:8
差:2
积:15
商:1
这是通过在同一个类的两个实例上调用相应的方法来执行算术运算的一个简单示例。你可以根据自己的需求和具体的运算逻辑来修改和扩展这个示例。