返回列表 發帖
  1. public class Ch08 {
  2.         public static void main(String[] args)
  3.         {
  4.                 Square sq=new Square("方形1","綠色",5);
  5.                 sq.showName();
  6.                 sq.showColor();
  7.                 sq.calArea();
  8.                 Tri tr=new Tri("三角形1","粉紅色",8,12);
  9.                 tr.showName();
  10.                 tr.showColor();
  11.                 tr.calArea();
  12.         }   
  13. }
  14. abstract class Shape
  15. {
  16.         String n, c;
  17.         Shape(String name, String color)
  18.         {
  19.                 n=name;
  20.                 c=color;
  21.         }
  22.         void showName()
  23.         {
  24.                 System.out.println("物件名稱: "+n);
  25.         }
  26.         void showColor()
  27.         {
  28.                 System.out.println("顏色為: "+c);
  29.         }
  30.         abstract void calArea();
  31. }

  32. class Square extends Shape
  33. {
  34.         int xx;
  35.         Square(String name, String color, int x)
  36.         {
  37.                 super(name,color);
  38.                 xx=x;
  39.         }  
  40.         void calArea() {
  41.                 System.out.println("面積為:"+xx*xx);
  42.         }
  43. }
  44. class Tri extends Shape
  45. {
  46.         double xx, yy;
  47.         Tri(String name, String color, double x, double y)
  48.         {
  49.                 super(name,color);
  50.                 xx=x;
  51.                 yy=y;
  52.         }  
  53.         void calArea()
  54.         {
  55.                 System.out.println("面積為: "+(xx*yy/2)+"平方公分");     
  56.         }
  57. }
複製代碼

TOP

返回列表