Wednesday, October 03, 2012

Java範例程式 : 抽象類別

範例中將星球(Planet)作為抽象類別, 以太陽(Sun)及地球(Earth)類別繼承抽象類別.

程式碼
abstract class Planet
{
 protected double size;
 protected double expect_life;
 protected int speed;

 public void setSize(double s)
 {
  size = s;
  System.out.println("大小為 " + size);
 }

 public void setSpeed(int s)
 {
  speed = s;
  System.out.println("速度為 " + speed);
 }

 public void setLife(double elife)
 {
  expect_life = elife;
  System.out.println("預計壽命為 " + expect_life);
 }

 abstract void show();
}

class Sun extends Planet
{
 private double solarpower;
 private static int ssum = 0;

 Sun()
 {
  System.out.println("創造了一個太陽");
  ssum++;
  super.setSize(6000.0*(Math.random() * 77));
  super.setSpeed(3600*(int)(Math.random() * 77));
  super.setLife(500000.0*(Math.random() * 77));
 }

 Sun(double spower)
 {
  this();
  this.setPower(spower);
 }

 public void setPower(double spower)
 {
  solarpower = spower;
  System.out.println("點燃火力 " + solarpower + " 的太陽");
 }

 public void show()
 {
  System.out.println("這是一個太陽 ( 火力 " + solarpower + " 大小 " + size + " 速度 " + speed + " 壽命 " + expect_life + " )");
 }

 public static void showSum()
 {
  System.out.println("共有 " + ssum + " 顆太陽");
 }
}

class Earth extends Planet
{
 private int creatures;
 private static int esum = 0;

 Earth()
 {
  System.out.println("創造一個地球");
  esum++;
  super.setSize(360.0*(Math.random() * 77));
  super.setSpeed(60*(int)(Math.random() * 77));
  super.setLife(6000.0*(Math.random() * 77));
 }

 Earth(int c)
 {
  this();
  this.setCreature(c);
 }

 public void setCreature(int c)
 {
  creatures = c;
  System.out.println("創造 " + creatures + " 種生命");
 }

 public void show()
 {
  System.out.println("這是一個有 " + creatures + " 種生命的地球( 大小 " + size + " 速度 " + speed + " 壽命 " + expect_life + " )");
 }

 public static void showSum()
 {
  System.out.println("共有 " + esum + " 顆地球");
 }
}

class C12P286
{
 public static void main(String[] args)
 {
  System.out.println("創世紀 : 星球篇");
  Planet[] P = new Planet[12];
  for(int i = 0; i < P.length; i++){
   if( i < 2 ){
    P[i] = new Sun((((double)(i+1)*(Math.random() * 10))*10000));
   } else {
    P[i] = new Earth(i*(int)(Math.random() * 77));
   }
  }

  System.out.println("\n創世紀報告");
  for(int i = 0; i < P.length; i++){
   System.out.print("星球 " + i + " ");
   if(P[i] instanceof Sun){ System.out.print("S "); }
   if(P[i] instanceof Earth){ System.out.print("E "); }
   P[i].show();
  }

  Sun.showSum();
  Earth.showSum();
 }
}

No comments: