TestComparableRectangle

来源:互联网 发布:js 对象 函数 编辑:程序博客网 时间:2024/06/17 20:03
// Interface for comparing objects, defined in java.lang

/** Find a maximum object */
class Max {
    public static Comparable max(Comparable c1, Comparable c2) {
        /** Return the maximum of two objects */
        if(c1.compareTo(c2) > 0)
            return c1;
        else
            return c2;
    }
}

/*interface Comparable {
    public abstract int compareTo(Object o);
}*/

class Rectangle {
    private double width;
    private double height;
    
    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }
    
    public double getArea() {
        return width * height;
    }
    
    public String toString() {
        return this.getClass() + ":\nwidth: " + width + " height: " + height;
    }
}

class ComparableRectangle extends Rectangle
implements Comparable {
    /** Construct a ComparableRectangle with specified properties */
    public ComparableRectangle(double width, double height) {
        super(width, height);
    }
    
    /** Implement the comparaTo method defined in the Comparable */
    public int compareTo(Object o) {
        if(this.getArea() < ((ComparableRectangle) o).getArea())
            return -1;
        else if(this.getArea() == ((ComparableRectangle) o).getArea())
            return 0;
        else
            return 1;
    }
}

public class TestComparableRectangle {
    public static void main(String[] args) {
        ComparableRectangle rectangle1 = new ComparableRectangle(1, 2);
        ComparableRectangle rectangle2 = new ComparableRectangle(2, 3);
        
        System.out.println(Max.max(rectangle1, rectangle2));
    }

}






class ComparableRectangle:
width: 2.0 height: 3.0





0 0