返回列表 發帖
  1. public class Ch02 {
  2.         public static void main(String[] args) {
  3.                 square s=new square("方形1號","綠色",5);
  4.                 s.showname();
  5.                 s.showcolor();
  6.                 s.calArea();
  7.                 tri t=new tri("三角形1號","粉紅色",7,5);
  8.                 t.showname();
  9.                 t.showcolor();
  10.                 t.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.         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 name,String color, int x)
  35.         {
  36.                 super(name, color);
  37.                 this.x=x;
  38.         }
  39.         void calArea()
  40.         {
  41.                 System.out.println("面積為: "+x*x+"平方公分");     
  42.         }
  43. }
  44. class tri extends shape
  45. {
  46.         double x, y;
  47.         tri(String name,String color,double x,double y)
  48.         {
  49.                 super(name,color);
  50.                 this.x=x;
  51.                 this.y=y;
  52.         }  
  53.         void calArea()
  54.         {
  55.                 System.out.println("面積為: "+(x*y/2)+"平方公分");     
  56.         }
  57. }
複製代碼

TOP

返回列表