(1)首先创建圆类Circle和圆柱体类Cylinder,其中Circle类是父类,Cylinder类是子类; (2)创建接口Comparable,其中包含一个抽象方法compareTo,用来比较对象的大小。抽象方法compareTo的形式如下: public int compareTo(Object o); (3)创建类ComparableCircle,该类为Circle类的子类,并实现Comparable接口。 (4)创建类ComparableCylinder,该类为Cylinder类的子类,并实现C
时间: 2023-12-06 10:44:29 浏览: 60
c++考试_圆和圆柱体_
omparable接口。
下面是代码实现:
Circle类:
```
public class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}
```
Cylinder类:
```
public class Cylinder extends Circle {
private double height;
public Cylinder(double radius, double height) {
super(radius);
this.height = height;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getVolume() {
return super.getArea() * height;
}
}
```
Comparable接口:
```
public interface Comparable {
public int compareTo(Object o);
}
```
ComparableCircle类:
```
public class ComparableCircle extends Circle implements Comparable {
public ComparableCircle(double radius) {
super(radius);
}
@Override
public int compareTo(Object o) {
if (o instanceof ComparableCircle) {
ComparableCircle c = (ComparableCircle) o;
if (this.getRadius() > c.getRadius()) {
return 1;
} else if (this.getRadius() < c.getRadius()) {
return -1;
} else {
return 0;
}
}
return -1;
}
}
```
ComparableCylinder类:
```
public class ComparableCylinder extends Cylinder implements Comparable {
public ComparableCylinder(double radius, double height) {
super(radius, height);
}
@Override
public int compareTo(Object o) {
if (o instanceof ComparableCylinder) {
ComparableCylinder c = (ComparableCylinder) o;
if (this.getVolume() > c.getVolume()) {
return 1;
} else if (this.getVolume() < c.getVolume()) {
return -1;
} else {
return 0;
}
}
return -1;
}
}
```
这样,我们就创建了Circle类和Cylinder类,并且Circle类是Cylinder类的父类,Comparable接口定义了一个抽象方法compareTo,用来比较对象的大小。我们还创建了ComparableCircle类和ComparableCylinder类,分别实现了Comparable接口,并重写了compareTo方法。这样,我们就可以使用这些类来进行比较操作了。
阅读全文