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

TOP

返回列表