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