学习内容:设计并实现加法器类 Adder
代码示例:
package 实验三;
import java.util.Scanner;
public class Adder {
private int num;
public Adder(int a) {
num=a;
System.out.println("Adder Constructor run");
}
public void setNum(int num) {
this.num=num;
}
public final int getNum() {
return num;
}
public final void show() {
System.out.println("Adder("+num+")");
}
public static void main(String[] args) {
int x,y;
Adder a1=new Adder(y=0);
Adder a3=a1;
System.out.println("请输入x:");
Scanner sc=new Scanner(System.in);
x=sc.nextInt();
a1.show();
y++;
Adder a2=new Adder(y);
a2.show();//代替(++a1).show()
++x;//代替(++a3).show()
a3.setNum(x);
a3.show();
Adder a4=new Adder(x+y);//代替(a1+a2).show()
a4.show();
}
}
运行截图:
遇到的问题:Java语言无法进行运算符重载,无法进行对象相加减
解决方法:用构造方法的参数相加减代替对象相加减
明天任务:设计并实现大数类 BigNum