三、同一个类的两个对象之间的交互
一个对象可以与同一个类的另一个对象交互从而完成程序所规定的任务。如果我们在Surface类中增加一个比较面积的方法。程序代码为:
public int compareAreas(Surface theOtherSurface){
final double precision=0.00001;
double area1=getArea();
double area2=theOtherSurface.getArea();
if (Math.abs(area2-area1)<precision) return 0;
else if(area1>area2) return –1;
else return 1;
}
final double precision=0.00001;
double area1=getArea();
double area2=theOtherSurface.getArea();
if (Math.abs(area2-area1)<precision) return 0;
else if(area1>area2) return –1;
else return 1;
}
在主程序FlooringClient中,我们可以实现如下代码
Surface surface1=new Surface("A",5,4);
Surface surface2=new Surface("B",4,4);
Int result=surface1.compareAreas(surface2);
If (result<0) System.out.println(surface1.getName()+"is the smaller one");
else If (result>0) System.out.println(surface2.getName()+"is the smaller one");
else System.out.println("The surface has the same area");
Surface surface2=new Surface("B",4,4);
Int result=surface1.compareAreas(surface2);
If (result<0) System.out.println(surface1.getName()+"is the smaller one");
else If (result>0) System.out.println(surface2.getName()+"is the smaller one");
else System.out.println("The surface has the same area");
从以上程序中可以看出,surface1与surface2发生交互从而得到结果result。首先它计算出自己的面积,然后计算出surface2的面积,最后再比较它们两个之间的面积的大小。
以上过程用UML序列图可以描述为下图:

以上详细说明了如何利用UML序列图来描述各类之间的对象或同一类不同之间的对象相互之间的交互序列过程。是Java应用程序面向对象设计过程中的一个重要方面。