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

  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 Tri("三角形1號","粉紅色",7,5);
  8.                 t1.showName();
  9.                 t1.showColor();
  10.                 t1.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 n ,String c,int x)
  35.         {
  36.                 super(n,c);
  37.                 this.x=x;
  38.         }       
  39.         void showName()
  40.         {
  41.                 System.out.println("物件名稱:"+name);
  42.         }
  43.         void showColor()
  44.         {
  45.                 System.out.println("顏色為:"+color);
  46.         }
  47.         void calArea()
  48.         {
  49.                 System.out.println("面積為:"+(x*x)+"平方公分");
  50.         }
  51. }
  52. class Tri extends Shape
  53. {
  54.         float x,y;
  55.         Tri(String n ,String c,float x,float y)
  56.         {
  57.                 super(n,c);
  58.                 this.y=y;
  59.                 this.x=x;
  60.         }       
  61.         void showName()
  62.         {
  63.                 System.out.println("物件名稱:"+name);
  64.         }
  65.         void showColor()
  66.         {
  67.                 System.out.println("顏色為:"+color);
  68.         }
  69.         void calArea()
  70.         {
  71.                 System.out.println("面積為:"+(x*y)/2+"平方公分");
  72.         }
  73. }
複製代碼

TOP

返回列表