- public class Ch08 {
- public static void main(String[] args)
- {
- Square sq=new Square("方形1","綠色",5);
- sq.showName();
- sq.showColor();
- sq.calArea();
- Tri tr=new Tri("三角形1","粉紅色",8,12);
- tr.showName();
- tr.showColor();
- tr.calArea();
- }
- }
- abstract class Shape
- {
- String n, c;
- Shape(String name, String color)
- {
- n=name;
- c=color;
- }
- void showName()
- {
- System.out.println("物件名稱: "+n);
- }
- void showColor()
- {
- System.out.println("顏色為: "+c);
- }
- abstract void calArea();
- }
- class Square extends Shape
- {
- int xx;
- Square(String name, String color, int x)
- {
- super(name,color);
- xx=x;
- }
- void calArea() {
- System.out.println("面積為:"+xx*xx);
- }
- }
- class Tri extends Shape
- {
- double xx, yy;
- Tri(String name, String color, double x, double y)
- {
- super(name,color);
- xx=x;
- yy=y;
- }
- void calArea()
- {
- System.out.println("面積為: "+(xx*yy/2)+"平方公分");
- }
- }
複製代碼 |