好的,我们先来创建这个名为Tuxing的抽象父类,它有一个抽象方法`getArea()`用于计算面积。abstract class Tuxing implements Comparable<Tuxing> { public abstract double getArea(); @Override public int compareTo(Tuxing other) { double area1 = this.getArea(); double area2 = other.getArea(); if (area1 < area2) { return -1; } else if (area1 > area2) { return 1; } else { return 0; } }}
接下来我们创建三个子类Yuan,SanJiao,JuXing,它们都继承自Tuxing父类,并重写`getArea()`方法。class Yuan extends Tuxing { private double radius; public Yuan(double radius) { this.radius = radius; } @Override public double getArea() { return Math.PI * radius * radius; }}class SanJiao extends Tuxing { private double base; private double height; public SanJiao(double base, double height) { this.base = base; this.height = height; } @Override public double getArea() { return base * height / 2; }}class JuXing extends Tuxing { private double length; private double width; public JuXing(double length, double width) { this.length = length; this.width = width; } @Override public double getArea() { return length * width; }}
最后,我们编写测试程序,创建10个子类对象存入ArrayList中,并按面积大小进行排序。import java.util.ArrayList;import java.util.Collections;import java.util.List;public class Main { public static void main(String[] args) { List<Tuxing> list = new ArrayList<>(); // 创建10个子类对象 list.add(new Yuan(3)); list.add(new Yuan(5)); list.add(new SanJiao(4, 6)); list.add(new SanJiao(2, 8)); list.add(new JuXing(2, 4)); list.add(new JuXing(5, 7)); list.add(new Yuan(2.5)); list.add(new SanJiao(3, 9)); list.add(new JuXing(3, 6)); list.add(new JuXing(4, 5)); // 按面积大小进行排序 Collections.sort(list); // 输出排序后的结果 for (Tuxing tuxing : list) { System.out.println(tuxing.getArea()); } }}
这样,我们就完成了题目需求,创建了10个子类对象,存入ArrayList中,并按面积大小进行排序输出。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |