返回列表 發帖
  1. public class Ch071601 {
  2.         public static void main(String[] args) {
  3.                 Square sq=new Square("方形1號", "綠色", 5);
  4.                 sq.showName();
  5.                 sq.showColor();
  6.                 sq.calArea();
  7.                 Tri tr=new Tri("三角形1號","粉紅色",7,5);
  8.         tr.showName();
  9.         tr.showColor();
  10.         tr.calArea();

  11.         }

  12. }

  13. abstract class Shape
  14. {
  15.         String name, color;
  16.         Shape(String n, String c)
  17.         {
  18.                 name=n;
  19.                 color=c;
  20.         }
  21.        
  22.         void showName()
  23.         {
  24.                 System.out.println("物件名稱: "+name);
  25.         }
  26.        
  27.         void showColor()
  28.         {
  29.                 System.out.println("顏色為: "+color);
  30.         }
  31.         abstract void calArea();
  32. }

  33. class Square extends Shape
  34. {
  35.     int x;
  36.     Square(String name, String color, int x)
  37.     {
  38.         super(name,color);
  39.         this.x=x;
  40.     }  
  41.     void calArea()
  42.     {
  43.         System.out.println("面積為: "+x*x+"平方公分");     
  44.     }
  45. }

  46. class Tri extends Shape
  47. {
  48.         double x, y;
  49.     Tri(String name, String color, double x, double y)
  50.     {
  51.         super(name,color);
  52.         this.x=x;
  53.         this.y=y;
  54.     }  
  55.     void calArea()
  56.     {
  57.         System.out.println("面積為: "+(x*y/2)+"平方公分");     
  58.     }
  59. }
複製代碼

TOP

返回列表