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

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

  13. abstract class Shape{
  14.         String color, name;

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

  27. class Square extends Shape{
  28.         int x;
  29.     Square(String n, String c, int x) {
  30.             super(n, c);
  31.             this.x=x;
  32.     }
  33.     void calArea(){
  34.             System.out.println("面積為: "+x*x+"平方公分");
  35.     }
  36. }

  37. class Tri extends Shape{
  38.         double x, y;
  39.         Tri(String n, String c, double x, double y) {
  40.                 super(n, c);
  41.                 this.x=x;
  42.                 this.y=y;
  43.         }
  44.         void calArea(){
  45.                 System.out.println("面積為: "+(x*y/2)+"平方公分");
  46.         }
  47. }
複製代碼

TOP

返回列表