抽象類別 Shape 宣告如下。perimeter() 為計算周長的方法,getType() 為抽象方法,傳回型態名稱字串。 public abstract class Shape { public double perimeter() { return 0.0; }; public abstract String getType() ; } 請設計一個類別 E0902 繼承 Shape 類別並實作 getType() 方法,當然 您也要設計一個真正計算周長的方法。以矩形測試之。
private String type; private double r; public void setR(double r) {
type = "circularity";
this.r = r;
} public double perimeter() {
return 2 * 3.1416 * r;
} public String getType() {
return type;
}
}
public class E0902 extends Shape {
private String type;
private double width,height; public void E0902(String tp,double wid,double hei) {
type = tp;
width=wid;
height=hei;
} public double perimeter() {
return 2 * (width + height);
} public String getType() {
return type;
}
}