复数相加+equels、hashcode、clone<一>
1 package com.jdk7.chapter1; 2 3 public class ComplexNumber { 4 5 private double realPart; 6 private double imagePart; 7 8 public double getRealPart() { 9 return realPart; 10 } 11 12 public void setRealPart(double realPart) { 13 this.realPart = realPart; 14 } 15 16 public double getImagePart() { 17 return imagePart; 18 } 19 20 public void setImagePart(double imagePart) { 21 this.imagePart = imagePart; 22 } 23 24 @Override 25 public String toString() { 26 return "realPart=" + realPart + ", imagePart=" + imagePart + "i"; 27 } 28 29 /** 30 * 默认构造函数 31 */ 32 public ComplexNumber(){ 33 this.realPart = 0.0; 34 this.imagePart = 0.0; 35 } 36 37 /** 38 * 自定义带参构造函数 39 * @param a 40 * @param b 41 */ 42 public ComplexNumber(double a,double b){ 43 this.realPart = a; 44 this.imagePart = b; 45 } 46 47 /** 48 * 复数相加 49 * 返回复数类型 50 * @return 51 */ 52 public ComplexNumber add(ComplexNumber comn){ 53 if(comn==null){ 54 System.err.println("对象不能为null"); 55 return new ComplexNumber(); 56 }else{ 57 return new ComplexNumber(this.realPart+comn.realPart,this.imagePart+comn.imagePart); 58 } 59 } 60 61 public static void main(String[] args) { 62 ComplexNumber a = new ComplexNumber(1,2); 63 // ComplexNumber a = new ComplexNumber(); 64 // ComplexNumber a = null; 65 ComplexNumber b = new ComplexNumber(1,2); 66 // ComplexNumber b = new ComplexNumber(); 67 // ComplexNumber b = null; 68 // 被加数不能为null 69 // System.out.println("(a+b) = "+a.add(b).toString()); 70 71 //a和b的值虽然相同,但是在声明为类类型变量时为不同的内存地址,object提供的equels方法比较的是内存地址 72 System.out.println("(a==b) : "+a.equals(b)); 73 //对象实例内存地址不同,hashcode也不相同 74 System.out.println("hashcode of a: "+a.hashCode()); 75 System.out.println("hashcode of b: "+b.hashCode()); 76 try { 77 System.out.println(a.clone()); 78 } catch (CloneNotSupportedException e) { 79 e.printStackTrace(); 80 } 81 82 } 83 84 }