Say there are GeometricObject, Circle, Rectangle class as follows:
Code:public abstract class GeometricObject extends Object implements Comparable<Object> {
public int prc;
public String color;
public void setColor(String color) {
this.color = color;
}
public abstract double getArea();
public static Comparable max(Comparable c1, Comparable c2) {
if (c1.compareTo(c2) > 1)
return c1;
else
return c2;
}
}
Code:public class Circle extends GeometricObject {
private double radius;
public int prc;
public Circle() {
super.prc = 1;
}
Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return radius * radius * Math.PI;
}
@Override
public int compareTo(Object o) {
if (getArea() > ((Circle) o).getArea()) {
return 1;
} else if (getArea() < ((Circle) o).getArea()) {
return -1;
} else {
return 0;
}
}
}
And a tester:Code:public class Rectangle extends GeometricObject {
private double width;
private double height;
public Rectangle() {
}
public Rectangle(double width, double height, String color) {
this.width = width;
this.height = height;
setColor(color);
}
/** Return area */
@Override
public double getArea() {
return width * height;
}
@Override
public int compareTo(Object o) {
if (getArea() > ((Rectangle) o).getArea()) {
return 1;
} else if (getArea() < ((Rectangle) o).getArea()) {
return -1;
} else {
return 0;
}
}
}
As I'm doing this exercize and do not have answer but I have You, I will appreciate if You could give me some answers on this matter.Code:public class TestCircleRectangle {
public static void main(String[] args) {
Circle c1 = new Circle(5);
Circle c2 = new Circle(7);
Rectangle r1 = new Rectangle(5, 5, "red");
Rectangle r2 = new Rectangle(7, 7, "red");
Comparable com1 = GeometricObject.max(r1, r2);//ok
Comparable com2 = GeometricObject.max(r1, c2);//error
}
}
Am I using Comparable interface right?
How I'm suppose to handle error comparing objects of type Circle and Rectangle?

