Java程序:
public class Main002 {
public static void main(String[] args) {
Calculator c1 = new Calculator(2);
Calculator c2 = new Calculator(3);
Calculator c3;
c3 = c1.add(c2);
System.out.println("c1 + c2 = " + c3.toString());
c3 = c1.subtract(c2);
System.out.println("c1 - c2 = " + c3.toString());
c3 = c1.product(c2);
System.out.println("c1 * c2 = " + c3.toString());
c3 = c1.divide(c2);
System.out.println("c1 / c2 = " + c3.toString());
}
}
//计算器类:Calculator,可以实现两个整数的加减乘除的运算
class Calculator {
protected int num;
//构造方法
public Calculator() {
num = 0;
}
//构造方法
public Calculator(int num) {
this.num = num;
}
//两个整数的相加运算
public Calculator add(Calculator c) {
return new Calculator(this.num + c.num);
}
//两个整数的相减运算
public Calculator subtract(Calculator c) {
return new Calculator(this.num - c.num);
}
//两个整数的相乘运算
public Calculator product(Calculator c) {
return new Calculator(this.num * c.num);
}
//两个整数的相除运算
public Calculator divide(Calculator c) {
return new Calculator(this.num / c.num);
}
public String toString() {
return String.valueOf(num);
}
}
运行测试:
c1 + c2 = 5
c1 - c2 = -1
c1 * c2 = 6
c1 / c2 = 0