- public class Ch01 {
- public static void main(String[] args) {
- Sqa s=new Sqa("方形一號","綠色",5);
- Tri t=new Tri("三角形一號","粉紅色",7,5);
- s.showName();
- s.showColor();
- s.calArea();
- 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 Sqa extends Shape{
- int x;
- Sqa(String n,String c,int x)
- {
- super(n,c);
- this.x=x;
- }
- void calArea()
- {
- System.out.println("面積: "+x*x+"平方公分");
- }
- }
- class Tri extends Shape{
- double x,y;
- Tri(String n,String c,double x,double y)
- {
- super(n,c);
- this.x=x;
- this.y=y;
- }
- void calArea()
- {
- System.out.println("面積: "+x*y/2+"平方公分");
- }
- }
複製代碼 |