JAVA---接口练习---比较对象大小

CompareObject.java

package exer;

public interface CompareObject {
	public int compareTo(Object o);
}

Circle.java

package exer;

public class Circle {
	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;
	}
}

ComparableCircle.java

package exer;

public class ComparableCircle extends Circle implements CompareObject{
	public ComparableCircle(double radius){
		super(radius);
	}
	public int compareTo(Object o){
		if(this== o){
			return 0;
		}
		if(o instanceof ComparableCircle){
			ComparableCircle c=(ComparableCircle)o;
			//如果小于,返回-1,如果大于,返回1,如果等于,返回0
			return this.getRadius().compareTo(c.getRadius());
		}else{
			throw new RuntimeException("传入的数据类型不匹配");
		}
	}
}

ComparableCircleTest.java

package exer;

public class ComparableCircleTest {
	public static void main(String[] args) {
		ComparableCircle c1=new ComparableCircle(7.7);
		ComparableCircle c2=new ComparableCircle(7.3);
		
		int compareValue = c1.compareTo(c2);
		if(compareValue>0){
			System.out.println("c1对象大");
		}else if(compareValue < 0){
			System.out.println("c2对象大");
		}else{
			System.out.println("一样大");
		}
		
		int compareValue1=c1.compareTo(new String("ss"));
		System.out.println(compareValue1);
	}
}

posted @ 2022-02-09 20:01  ice--cream  阅读(59)  评论(0编辑  收藏  举报