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

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

  12. }

  13. abstract class shape {
  14.         String name, color;
  15.        
  16.         shape(String name, String color) {
  17.                 this.name = name;
  18.                 this.color = color;
  19.         }
  20.        
  21.         void showName() {
  22.                 System.out.println("物件名稱:" + name);
  23.         }
  24.        
  25.         void showColor() {
  26.                 System.out.println("顏色為:" + color);
  27.         }
  28.        
  29.         abstract void calArea();
  30. }

  31. class Square extends shape {
  32.         int x;
  33.        
  34.         Square(String name, String color, int x) {
  35.                 super(name, color);
  36.                 this.x = x;
  37.         }

  38.         void calArea() {
  39.                 System.out.println("面積為:"+(x*x)+"平方公分");
  40.         }
  41. }


  42. class Tri extends shape {
  43.         float x, y;

  44.         Tri(String name, String color, float x, float y) {
  45.                 super(name, color);
  46.                 this.x = x;
  47.                 this.y = y;
  48.         }

  49.         void calArea() {
  50.                 System.out.println("面積為:"+(x*y/2)+"平方公分");
  51.         }
  52.        
  53. }
複製代碼

TOP

返回列表