interface代码示例
import javax.management.RuntimeErrorException;
interface CompareObject {
//返回0,代表相等;正数,代表当前对象大;负数代表当前对象小
public int compareTo(Object o);
}
class Circle { //radius私有成员变量,定义了变量的get和set方法,以及空参和radius变量的两个构造器 private Double radius; public Double getRadius() { return radius; } public void setRadius(double radius) { this.radius = radius; } public Circle() { super(); } public Circle(Double radius) { super(); this.radius = radius; } } class ComparableCircle extends Circle implements CompareObject { public ComparableCircle(double radius) { super(radius); } @Override public int compareTo(Object o) { if(this == o ) { return 0; } else if(o instanceof ComparableCircle){ ComparableCircle c = (ComparableCircle)o; // return (int)(this.getRadius()-c.getRadius());精度损失 // //方法2,用if比较double类型的radius的大小 // if(this.getRadius()>c.getRadius()){ // return 1; // } // else if(this.getRadius()<c.getRadius()) { // return -1; // } // else { // return 0; // } //方法3:radius声明为包装类Double类型,可以使用包装类的方法 return this.getRadius().compareTo(c.getRadius()); } else { // return 0; throw new RuntimeException("传入数据类型不匹配"); } } } public class ComparableCircleTest { public static void main(String[] args) { ComparableCircle c1= new ComparableCircle(3.4); ComparableCircle c2 = new ComparableCircle(3.6); int comparevalue = c1.compareTo(c2); if(comparevalue > 0) { System.out.println("c1大"); } else if(comparevalue <0) { System.out.println("c2大");
} else if (comparevalue == 0) { System.out.println("一样大"); } int comparevalue2 = c1.compareTo("as"); System.out.println(comparevalue2); } }