java

来源:互联网 发布:虚拟机安装ubuntu系统 编辑:程序博客网 时间:2024/05/01 21:10
public void add(Complex c) //两个对象相加 { //改变当前对象,没有返回新对象 this.real += c.real; this.im += c.im; } public Complex plus(Complex c) //两个对象相加,与add()方法参数一样不能重载 { //返回新创建对象,没有改变当前对象 return new Complex(this.real+c.real, this.im+c.im); } public void subtract(Complex c) //两个对象相减 { //改变当前对象,没有返回新对象 this.real -= c.real; this.im -= c.im; } public Complex minus(Complex c) //两个对象相减,与subtract()方法参数一样不能重载 { //返回新创建的对象,没有改变当前对象 return new Complex(this.real-c.real, this.im-c.im); } } class Complex__ex { public static void main(String args[]) { Complex a = new Complex(1,2); Complex b = new Complex(3,5); Complex c = a.plus(b); //返回新创建对象 System.out.println(a+" + "+b+" = "+c); } } /* 程序运行结果如下: (1.0+2.0i) + (3.0+5.0i) = (40.0+7.0i) */