返回列表 發帖
  1. public class Morris {

  2.         public static void main(String[] args) {
  3.                 // TODO 自動產生的方法 Stub
  4.                 square sq = new square("方形一號", "綠色", 5);
  5.                 sq.showName();
  6.                 sq.showColor();
  7.                 sq.calArea();
  8.                 triangle tri = new triangle("三角形一號", "粉紅色", 7, 5);
  9.                 tri.showName();
  10.                 tri.showColor();
  11.                 tri.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 triangle extends shape
  46. {
  47.         double b, h;
  48.         triangle(String name, String color, double b, double h)
  49.         {
  50.                 super(name, color);
  51.                 this.h = h;
  52.                 this.b = b;
  53.         }
  54.         void calArea()
  55.         {
  56.                 System.out.println("面積為: "+b*h/2+"平方公分");
  57.         }
  58. }
複製代碼

TOP

返回列表