Anonymous
Anonymous asked in 電腦與網際網路程式設計 · 1 decade ago

java父類別加入抽象方法

(a) 在父類別 Shape裡加入一個抽象方法area()。

(b)建立一個Circle類別,使得 Circle 繼承自 Shape 類別。並實作父類別的 area() ,子類別的 area()方法可用來計算圓的面積。

(c)建立一個Rectangle類別,使得 Rectangle 繼承自 Shape 類別。並實作父類別的 area() ,子類別的 area()方法可用來計算矩形的面積。

(d)在main()方法中建立父類別的陣列變數,再利用陣列元素建立子類別的物件。

Shape shp[] = new Shape[2];

shp[0] = new Circle(10);

shp[1} = new Rectangle(3,5);

(e) 撰寫一類別方法 largest(Shape[] shp),可找出面積最大者。

1 Answer

Rating
  • 1 decade ago
    Favorite Answer

    請參考我的做法

    abstract class Shape implements Comparable {

    abstract double area();

    public int compareTo(Object obj) {

    double d = area() - ((Shape)obj).area();

    if (d > 0) return 1;

    else if (d < 0) return -1;

    else return 0;

    }

    }

    class Circle extends Shape {

    double r;

    Circle(double d) {

    r = d;

    }

    double area() {

    return Math.PI * r * r;

    }

    public String toString() {

    return "Circle: " + r + " (area: " + area() + ")";

    }

    }

    class Rectangle extends Shape {

    double l, w;

    Rectangle(double d1, double d2) {

    l = d1;

    w = d2;

    }

    double area() {

    return l * w;

    }

    public String toString() {

    return "Rectangle: " + l + ", " + w + " (area: " + area() + ")";

    }

    }

    public class A {

    public static void main(String[] args) {

    Shape shp[] = new Shape[2];

    shp[0] = new Circle(10);

    shp[1] = new Rectangle(3,5);

    System.out.println(largest(shp));

    }

    public static Shape largest(Shape[] ary) {

    java.util.Arrays.sort(ary);

    return ary[ary.length-1];

    }

    }

Still have questions? Get your answers by asking now.