- public class Ch02 {
- 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 n,String c)
- {
- name=n;
- color=c;
- }
- 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
- {
- double x, y;
- tri(String name,String color,double x,double y)
- {
- super(name,color);
- this.x=x;
- this.y=y;
- }
- void calArea()
- {
- System.out.println("面積為: "+(x*y/2)+"平方公分");
- }
- }
複製代碼 |