package chapter12.lab1;
//使用抽象類別
//使用abstract 關鍵字
abstract class Vehicle
{
protected int speed;
public void setSpeed(int s)
{
speed = s;
System.out.println("已經將速度設定為"+speed);
}
//抽象類別的 show
abstract void show();
}
class Car extends Vehicle
{
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);
System.out.println("油量為"+gas);
System.out.println("速度是"+speed);
}
}
class Plane extends Vehicle
{
private int flight;
public Plane(int f)
{
flight =f;
System.out.println("已經初始化"+flight+"班次飛機");
}
public void show()
{
System.out.println("飛機班次是"+flight);
System.out.println("速度是"+speed);
}
}
public class Sample1 {
public static void main(String[] args) {
//使用抽象類別產生陣列
Vehicle vc[];
vc = new Vehicle[2];
//第一個物件是 Car 類別
vc[0] = new Car(1234, 20.5);
vc[0].setSpeed(60);
//第2個物件是 Plane類別
vc[1] = new Plane(232);
vc[1].setSpeed(500);
for(int i=0; i<vc.length; i++)
{
vc[i].show();
}
}
}
package chapter12.lab2;
//使用 instanceof 運算子
//使用abstract 關鍵字
abstract class Vehicle
{
protected int speed;
public void setSpeed(int s)
{
speed = s;
System.out.println("已經將速度設定為"+speed);
}
//抽象類別的 show
abstract void show();
}
class Car extends Vehicle
{
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);
System.out.println("油量為"+gas);
System.out.println("速度是"+speed);
}
}
class Plane extends Vehicle
{
private int flight;
public Plane(int f)
{
flight =f;
System.out.println("已經初始化"+flight+"班次飛機");
}
public void show()
{
System.out.println("飛機班次是"+flight);
System.out.println("速度是"+speed);
}
}
public class Sample2 {
public static void main(String[] args) {
Vehicle vc[];
vc = new Vehicle[2];
vc[0] = new Car(1234, 20.5);
vc[1] = new Plane(232);
for (int i=0; i< vc.length; i++)
{
//使用 instanceof 運算子判斷
if(vc[i] instanceof Car)
{
System.out.println("第"+(i+1)+"個物件是Car類別");
}
else
{
System.out.println("第"+(i+1)+"個物件不是Car類別");
}
}
}
}
沒有留言:
張貼留言