返回列表 發帖
  1. package ch02;

  2. public class ch03 {

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

  12.         }

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

TOP

返回列表