题目:
通过继承和多态的学习,同学们熟悉了GeometricObject类,现在用抽象类的观点,修改GeometricObject类以实现Comparable接口,且在GeometricObject类中定义一个静态方法:求两个GeometricObject对象中较大者。
此题提交时将会附加下述代码到被提交的Java程序末尾。
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Circle circle1 = new Circle(input.nextInt());
Circle circle2 = new Circle(input.nextInt());
Circle circle = (Circle) GeometricObject.max(circle1, circle2);
System.out.println("The max circle's radius is " + circle.getRadius());
System.out.println(circle);
}
}
/* 请在这里填写答案 */
输入样例:
4 10
输出样例:
The max circle's radius is 10.0
Circle radius = 10.0
答案:abstract class GeometricObject implements Comparable<GeometricObject> {
private String color = "white";
private boolean filled;
private java.util.Date dateCreated;
public static GeometricObject max(GeometricObject o1, GeometricObject o2) {
if (o1.compareTo(o2)>1)
return o1;
else {
return o2;
}
}
/** Construct a default geometric object */
protected GeometricObject() {
dateCreated = new java.util.Date();
}
/** Construct a geometric object with color and filled value */
protected GeometricObject(String color, boolean filled) {
dateCreated = new java.util.Date();
this.color = color;
this.filled = filled;
}
/** Return color */
public String getColor() {
return color;
}
/** Set a new color */
public void setColor(String color) {
this.color = color;
}
/**
* Return filled. Since filled is boolean, the get method is named isFilled
*/
public boolean isFilled() {
return filled;
}
/** Set a new filled */
public void setFilled(boolean filled) {
this.filled = filled;
}
/** Get dateCreated */
public java.util.Date getDateCreated() {
return dateCreated;
}
@Override
public String toString() {
return "created on " + dateCreated + "\ncolor: " + color + " and filled: " + filled;
}
/** Abstract method getArea */
public abstract double getArea();
/** Abstract method getPerimeter */
public abstract double getPerimeter();
}
class Circle extends GeometricObject {
double radius;
/** Construct a circle with radius 1 */
Circle() {
radius = 1;
}
/** Construct a circle with a specified radius */
Circle(double newRadius) {
radius = newRadius;
}
/** Return the area of this circle */
public double getArea() {
return radius * radius * Math.PI;
}
/** Return the perimeter of this circle */
public double getPerimeter() {
return 2 * radius * Math.PI;
}
/** Set a new radius for this circle */
void setRadius(double newRadius) {
radius = newRadius;
}
double getRadius() {
return radius;
}
public int compareTo(GeometricObject o) {
if (this.getArea() > o.getArea())
return 1;
if (this.getArea() < o.getArea())
return -1;
else if (this.getArea() > o.getArea())
return 1;
return 0;
}
public String toString() {
return String.format("Circle radius = %.1f", radius);
}
}