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

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


  14. abstract class Shape{
  15.         String name;
  16.         String color;
  17.         Shape(String n,String c)
  18.         {
  19.                 name=n;
  20.                 color=c;
  21.         }
  22.         void showName()
  23.         {
  24.                 System.out.println("物件名稱: "+name);
  25.         }
  26.         void showColor()
  27.         {
  28.                 System.out.println("顏色: "+color);
  29.         }
  30.         abstract void calArea();
  31. }
  32. class Square extends Shape{
  33.         int x;
  34.         Square(String n,String c,int x)
  35.         {
  36.                 super(n,c);
  37.                 this.x=x;
  38.         }
  39.         @Override
  40.         void calArea() {
  41.                 System.out.println("面積: "+(x*x)+"平方公分");
  42.         }
  43. }
  44. class Tri extends Shape{
  45.         double x,y;
  46.         Tri(String n,String c,double x,double y){
  47.                 super(n,c);
  48.                 this.x=x;
  49.                 this.y=y;
  50.         }
  51.         @Override
  52.         void calArea() {
  53.                 System.out.println("面積: "+(x*y)/2+"平方公分");
  54.         }
  55. }
複製代碼

TOP

返回列表