1. 程式人生 > >定義一個圖形類及其子類(三角形類和矩形類),分別計算其面積和周長。(第十週)

定義一個圖形類及其子類(三角形類和矩形類),分別計算其面積和周長。(第十週)

/*
 * 定義一個圖形類及其子類(三角形類和矩形類),分別計算其面積和周長。
 */
class Graphical {//父類
public double width;//成員變數
public double length;
public double area;
public double Perimeter;
public double areaGraphical() {//成員方法
return area;
}
public double PerimeterGraphical() {
return Perimeter;
}
}
class rectangle extends Graphical {//子類繼承父類
public double areaGraphical() {
area = width * length;
return area;
}
public double PerimeterGraphical() {
Perimeter = (width + length) * 2;
return Perimeter;
}
}
class Triangle extends Graphical {//子類繼承父類
public double high;
public double bottom;
public double side;
public double areaGraphical() {
area = (bottom * high) / 2;
return area;
}
public double PerimeterGraphical() {
Perimeter = high + bottom + side;
return Perimeter;
}
}
public class Sanjux {//主類
public static void main(String[] args) {
rectangle p1 = new rectangle();// 宣告物件和建立物件
p1.width = 10;
p1.length = 20;
p1.areaGraphical();
p1.PerimeterGraphical();
System.out.println("矩形面積:" + p1.areaGraphical() + "矩形周長:" + p1.PerimeterGraphical());//輸出
Triangle p2 = new Triangle();// 宣告物件和建立物件
p2.high = 5;
p2.side = 10;
p2.bottom = 6;
p2.areaGraphical();
p2.PerimeterGraphical();
System.out.println("三角形面積:" + p2.areaGraphical() + "三角形周長:" + p2.PerimeterGraphical());//輸出
}
}