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