返回列表 發帖
本帖最後由 王秉鈞 於 2022-9-17 20:55 編輯
  1. public abstract class Ch34 {

  2.         public static void main(String[] args) {
  3.         Square q1=new Square("方形1號","綠色",5);
  4.         q1.showName();
  5.         q1.showColor();
  6.         q1.calArea();
  7.         Tri t1=new Square("三角形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 name,String color)
  17.            {
  18.                    this.name=name;
  19.                    this.color=color;
  20.            }
  21.            void showName()
  22.            {
  23.                    System.out.println("物件名稱:"+name);
  24.            }
  25.            void showColor()
  26.            {
  27.                    System.out.println("顏色為:"+color);
  28.            }
  29.            abstract void calArea();
  30.    }
  31.    class Square extends Shape
  32.    {
  33.            int x;
  34.            Square(String n,String c,int x)
  35.            {
  36.                    super(n,c);
  37.                    this.x=x;
  38.            }
  39.            void calArea(){
  40.                    System.out.println("面積為:"+(x*x)+"平方公分");
  41.            }
  42.   }
  43.    class Tri extends Shape
  44.    {
  45.            double x,y;
  46.            Tri(String s,String c,double x,double y)
  47.            {
  48.                    super(s,c);
  49.                    this.x=x;
  50.                    this.y=y;
  51.            }
  52.            void calArea()
  53.            {
  54.                    System.out.println("面積為"+(x*y/2)+"平方公分");
  55.            }
  56. }
複製代碼

TOP

返回列表