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

  2.         public static void main(String[] args) {
  3.             Square sq=new Square("方形1號","綠色",5);
  4.             sq.showName();
  5.             sq.showColor();
  6.             sq.calArea();
  7.             
  8.             Tri tr=new Tri("三角形1號","粉紅色",7,5);
  9.             tr.showName();
  10.             tr.showColor();
  11.             tr.calArea();
  12.         }
  13. }
  14. abstract class Shape
  15. {
  16.         String name,color;
  17.        
  18.         Shape(String n,String c)
  19.         {
  20.                 name=n;
  21.                 color=c;
  22.         }
  23.         void showName()
  24.         {
  25.                 System.out.println("物件名稱:"+name);
  26.         }
  27.         void showColor()
  28.         {
  29.                 System.out.println("顏色為:"+color);
  30.         }
  31.        
  32.         abstract void calArea();
  33. }

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

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

TOP

返回列表