kk258966

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

May 27th, 2015
394
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.10 KB | None | 0 0
  1. // app11_1, 抽象類別的實例
  2. abstract class CShape               // 定義抽象類別CShape
  3. {
  4.    protected String color;       // 資料成員
  5.    public void setColor(String str)    // 一般的函數
  6.    {
  7.       color=str;
  8.    }
  9.    public abstract void show(); // 抽象函數,只有定義名稱,沒有定義處理方式
  10. }
  11.  
  12. class CRectangle extends CShape    // 定義子類別CRectangle
  13. {
  14.    protected int width,height;
  15.    public CRectangle(int w,int h)
  16.    {
  17.       width=w;
  18.       height=h;
  19.    }
  20.    public void show()      // 明確定義繼承自抽象類別的show() method
  21.    {
  22.       System.out.print("color="+color+",  ");
  23.       System.out.println("area="+width*height);
  24.    }
  25. }
  26.  
  27. class CTriangle extends CShape    // 定義子類別CRectangle
  28. {
  29.    protected int width,height;
  30.    public CTriangle(int w,int h)
  31.    {
  32.       width=w;
  33.       height=h;
  34.    }
  35.    public void show()      // 明確定義繼承自抽象類別的show() method
  36.    {
  37.       System.out.print("color="+color+",  ");
  38.       System.out.println("area="+width*height/2);
  39.    }
  40. }
  41. class CCircle extends CShape     // 定義子類別CCircle
  42. {
  43.    protected double radius;
  44.    public CCircle(double r)
  45.    {
  46.       radius=r;
  47.    }
  48.    public void show()     // 明確定義繼承自抽象類別的show() method
  49.    {
  50.       System.out.print("color="+color+",  ");
  51.       System.out.println("area="+3.14*radius*radius);
  52.    }
  53. }
  54. public class app11_1
  55. {
  56.    public static void main(String args[])
  57.    {
  58.       CRectangle rect=new CRectangle(5,10);
  59.       rect.setColor("Yellow");   // 呼叫父類別裡的setColor() method
  60.       rect.show();         // 呼叫CRectangle類別裡的show() method
  61.  
  62.       CCircle cir=new CCircle(2.0);
  63.       cir.setColor("Green");     // 呼叫父類別裡的setColor() method
  64.       cir.show();             // 呼叫CCircl類別裡的show() method
  65.      
  66.       CTriangle tri=new CTriangle(10,5);
  67.       tri.setColor("Pink");     // 呼叫父類別裡的setColor() method
  68.       tri.show();             // 呼叫CCircl類別裡的show() method
  69.      
  70.       System.out.println("B10207081");
  71.    }
  72.    
  73. }
Advertisement
Add Comment
Please, Sign In to add comment