- public class Ch71 {
- public static void main(String[] args) {
- Square s = new Square("方形1號","綠色",5);
- s.showName();
- s.showColor();
- s.calArea();
- Tri t = new Tri("三角形1號","粉紅色",7,5);
- t.showName();
- t.showColor();
- t.calArea();
- }
- }
- abstract class shape {
- String name, color;
-
- shape(String name, String color) {
- this.name = name;
- this.color = color;
- }
-
- void showName() {
- System.out.println("物件名稱:" + name);
- }
-
- void showColor() {
- System.out.println("顏色為:" + color);
- }
-
- abstract void calArea();
- }
- class Square extends shape {
- int x;
-
- Square(String name, String color, int x) {
- super(name, color);
- this.x = x;
- }
- void calArea() {
- System.out.println("面積為:"+(x*x)+"平方公分");
- }
- }
- class Tri extends shape {
- float x, y;
- Tri(String name, String color, float x, float y) {
- super(name, color);
- this.x = x;
- this.y = y;
- }
- void calArea() {
- System.out.println("面積為:"+(x*y/2)+"平方公分");
- }
-
- }
複製代碼 |