Wednesday, October 03, 2012

Java範例程式 : 界面

以車(Car)及飛機(Plane)類別實作界面(iVehicle).

程式碼
interface iVehicle
{
 void show();
}

class Car implements iVehicle
{
 private int num;
 private double gas;

 public Car(int n, double g)
 {
  num = n;
  gas = g;
  System.out.println("生產了車號 " + num + " 油量 " + gas + " 的汽車");
 }

 public void show()
 {
  System.out.println("這是車號 " + num + " 油量 " + gas + " 的汽車");
 }
}

class Plane implements iVehicle
{
 private int flight;

 public Plane(int f)
 {
  flight = f;
  System.out.println("生產了編號 " + flight + " 的飛機");
 }

 public void show()
 {
  System.out.println("這是編號 " + flight + " 的飛機");
 }
}

class C12P293
{
 public static void main(String[] args)
 {
  iVehicle[] ivc;
  ivc = new iVehicle[3];

  ivc[0] = new Car(1, 2000.0);
  ivc[1] = new Plane(6);
  ivc[2] = new Plane(7);

  System.out.println("\n調查生產成果");
  for(int i = 0; i < ivc.length; i++){
   System.out.print("序號 " + i + " ");
   ivc[i].show();
  }
 }
}

No comments: