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