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

  2.         public static void main(String[] args)
  3.         {
  4.                 Square s1 = new Square("方形1號","綠色",5);
  5.                 Triangle tr1 = new Triangle("三角形1號","粉紅色",7,5);
  6.                 s1.showName();
  7.                 s1.showColor();
  8.                 s1.calArea();
  9.                 tr1.showName();
  10.                 tr1.showColor();
  11.                 tr1.calArea();
  12.         }

  13. }

  14. abstract class Shape
  15. {
  16.         String name,color;
  17.         Shape(String n,String c)
  18.         {
  19.                 name=n;
  20.                 color=c;
  21.         }
  22.        
  23.         void showName()
  24.         {
  25.                 System.out.println("物件名稱: "+name);               
  26.         }
  27.        
  28.         void showColor()
  29.         {
  30.                 System.out.println("物件顏色: "+color);
  31.         }
  32.        
  33.         abstract void calArea();
  34. }

  35. class Square extends Shape
  36. {
  37.     int x;
  38.         Square(String n,String c,int x)
  39.         {
  40.                 super(c,n);
  41.                 this.x = x;
  42.         }
  43.        
  44.         void calArea()
  45.         {
  46.                 System.out.println("面積為: "+(x*x)+"平方公分" );
  47.         }
  48. }

  49. class Triangle extends Shape
  50. {
  51.     double x,y;
  52.         Triangle(String n,String c,double x,double y)
  53.         {
  54.                 super(c,n);
  55.                 this.x = x;
  56.                 this.y = y;
  57.         }
  58.        
  59.         void calArea()
  60.         {
  61.                 System.out.println("面積為: "+(x*y/2)+"平方公分" );
  62.         }
  63. }
複製代碼

TOP

返回列表