返回列表 發帖
  1. public class Ch01
  2. {
  3.         public static void main(String[] args)
  4.         {
  5.         Square s1=new Square("方形1號","綠色",5);
  6.         Tri t1=new Tri("三角形1號","粉紅色",7,5);
  7.         s1.showName();
  8.         s1.showColor();
  9.         s1.calArea();
  10.         t1.showName();
  11.         t1.showColor();
  12.         t1.calArea();
  13.         }
  14. }
  15. abstract class Shape
  16. {
  17.         String name;
  18.         String color;
  19.         Shape(String n,String c)
  20.         {
  21.                 name=n;
  22.                 color=c;
  23.         }
  24.         void showName()
  25.         {
  26.                 System.out.println("物件名稱: "+name);
  27.         }
  28.         void showColor()
  29.         {
  30.                 System.out.println("顏色為: "+color);
  31.         }
  32.         abstract void calArea();
  33. }
  34. class Square extends Shape
  35. {
  36.         int x;
  37.         Square(String n,String c,int x)
  38.         {
  39.                 super(n,c);
  40.                 this.x=x;
  41.         }
  42.         void calArea()
  43.         {
  44.                 System.out.println("面積為: "+(x*x)+"平方公里");
  45.         }
  46. }
  47. class Tri extends Shape
  48. {
  49.         double x,y;
  50.         Tri(String n,String c,double x,double y)
  51.         {
  52.                 super(n,c);
  53.                 this.x=x;
  54.                 this.y=y;
  55.         }
  56.         void calArea()
  57.         {
  58.                 System.out.println("面積為: "+(x*y)/2+"平方公里");
  59.         }
  60. }
複製代碼
Ivy

TOP

返回列表