- public class Morris {
- public static void main(String[] args) {
- // TODO 自動產生的方法 Stub
- square sq = new square("方形一號", "綠色", 5);
- sq.showName();
- sq.showColor();
- sq.calArea();
- triangle tri = new triangle("三角形一號", "粉紅色", 7, 5);
- tri.showName();
- tri.showColor();
- tri.calArea();
- }
- }
- abstract class shape
- {
- String name, color;
- shape(String name, String color)
- {
- this.name = name;
- this.color = color;
- }
- void showName()
- {
- System.out.println("物件名稱: "+name);
- }
- void showColor()
- {
- System.out.println("顏色為: "+color);
- }
- abstract void calArea();
- }
- class square extends shape
- {
- int x;
- square(String name, String color, int x)
- {
- super(name, color);
- this.x = x;
- }
- void calArea()
- {
- System.out.println("面積為: "+x*x+"平方公分");
- }
- }
- class triangle extends shape
- {
- double b, h;
- triangle(String name, String color, double b, double h)
- {
- super(name, color);
- this.h = h;
- this.b = b;
- }
- void calArea()
- {
- System.out.println("面積為: "+b*h/2+"平方公分");
- }
- }
複製代碼 |