Advertisement
kk258966

5/26 物件導向程式設計 練習二

May 27th, 2015
279
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.36 KB | None | 0 0
  1. interface iShape2D               // 定義介面
  2. {
  3.    final double PI=3.14;
  4.    abstract void area();
  5. }
  6.  
  7. class CRectangle implements iShape2D // 以CRectangle類別實作iShape2D介面
  8. {
  9.    int width,height;
  10.    public CRectangle(int w,int h)
  11.    {
  12.       width=w;
  13.       height=h;
  14.    }
  15.    public void area()      // 定義area()的處理方式
  16.    {
  17.       System.out.println("area="+width*height);
  18.    }
  19. }
  20.  
  21. class CCircle implements iShape2D // 以CCircle類別實作iShape2D介面
  22. {
  23.    double radius;
  24.    public CCircle(double r)
  25.    {
  26.       radius=r;
  27.    }
  28.    public void area()      // 定義area()的處理方式
  29.    {
  30.       System.out.println("area="+PI*radius*radius);
  31.    }
  32. }
  33.  
  34. class CTriangle implements iShape2D // 以CCircle類別實作iShape2D介面
  35. {
  36.    int width,height;
  37.   public CTriangle(int w,int h)
  38.    {
  39.       width=w;
  40.       height=h;
  41.    }
  42.    public void area()      // 定義area()的處理方式
  43.    {
  44.       System.out.println("area="+width*height/2);
  45.    }
  46. }
  47.  
  48. public class app11_4
  49. {
  50.    public static void main(String args[])
  51.    {
  52.       CRectangle rect=new CRectangle(5,10);
  53.       rect.area();         // 呼叫CRectangle類別裡的area() method
  54.  
  55.       CCircle cir=new CCircle(2.0);
  56.       cir.area();
  57.      
  58.       CTriangle tri=new CTriangle(20,10);
  59.       tri.area();        // 呼叫CCircle類別裡的area() method
  60.    }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement