返回列表 發帖
  1. public class Ch71 {
  2.         public static void main(String[] args) {
  3.                 Square q1=new Square("方形1號","綠色",5);
  4.                 q1.showName();
  5.                 q1.showColor();
  6.                 q1.calArea();
  7.                 Tri t1=new Tri("三角形1號","粉紅色",7,5);
  8.                 t1.showName();
  9.                 t1.showColor();
  10.                 t1.calArea();
  11.         }
  12. }
  13. abstract class shape{
  14.         String name,color;
  15.         shape(String n,String c){
  16.                 name=n;
  17.                 color=c;
  18.         }
  19.         void showName()
  20.         {
  21.                 System.out.println("物件名稱:"+name);
  22.         }
  23.         void showColor()
  24.         {
  25.                 System.out.println("顏色為:"+color);
  26.         }
  27.         abstract void calArea();
  28. }
  29. class Square extends shape
  30. {
  31.         int x;
  32.         Square(String n, String c, int x)
  33.         {
  34.                 super(n, c);
  35.                 this.x=x;
  36.         }
  37.         void calArea()
  38.         {
  39.                 System.out.println("面積為:"+x*x+"平方公分");
  40.         }
  41. }
  42. class Tri extends shape{
  43.         float x,y;
  44.         Tri(String n,String c,float x,float y)
  45.         {
  46.                 super(n,c);
  47.                 this.x=x;
  48.                 this.y=y;
  49.         }
  50.         void calArea()
  51.         {
  52.                 System.out.println("面積為:"+x*y/2+"平方公分");
  53.         }
  54. }
複製代碼

TOP

返回列表