展开全部
public class TestInterface {
public static void main(String[] args) {
62616964757a686964616fe78988e69d8331333337623431ComparableCircle obj1 = new ComparableCircle(3.21);
ComparableCircle obj2 = new ComparableCircle(4.21);
int flag = obj1.compareTo(obj2);
System.out.println(flag);
ComparableRectangle o1 = new ComparableRectangle(4.3, 4.5);
ComparableRectangle o2 = new ComparableRectangle(4.8, 4.5);
int flag2 = o1.compareTo(o2);
System.out.println(flag2);
}
}
interface CompareObject{
public int compareTo(Object o);
}
class Circle{
private double rate; //半径
public Circle(double rate){
this.rate = rate;
}
public double getRate(){
return this.rate;
}
}
class ComparableCircle extends Circle implements CompareObject{
public int compareTo(Object o) {
if(this == o){
return 0;
}else if(o != null && o instanceof ComparableCircle){
ComparableCircle obj = (ComparableCircle)o;
if(this.getRate() > obj.getRate()){
return 1;
}else if(this.getRate() == obj.getRate()){
return 0;
}else{
return -1;
}
}else{
return -1;
}
}
public ComparableCircle(double rate){
super(rate);
}
}
class Rectangle{
private double width;
private double height;
public Rectangle(double width, double height){
this.width = width;
this.height = height;
}
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}
}
class ComparableRectangle extends Rectangle implements CompareObject{
public int compareTo(Object o) {
if(this == o){
return 0;
}else if(o != null && o instanceof ComparableRectangle){
ComparableRectangle obj = (ComparableRectangle)o;
if((this.getWidth() * this.getHeight()) > (obj.getWidth() * obj.getHeight())){
return 1;
}else if((this.getWidth() * this.getHeight()) == (obj.getWidth() * obj.getHeight())){
return 0;
}else{
return -1;
}
}else{
return -1;
}
}
public ComparableRectangle(double width, double height){
super(width,height);
}
}