2015年9月11日 星期五

Java 抽象類別

Java 抽象類別的使用:(hint: 把所有類別重複的東西,描象化成一個 super 類別!)
public abstract class Vehicle{
  
   private int wheels;
   private String engineType;
   private double weight;

   Vehicle(int wheels, String engineType, double weight){
       setWheels(wheels);
       setEngineType(engineType);
       setWeight(weight);
   }

   public abstract void ignite(); //這是抽象方法

   public int getWheels(){
     return this.wheels;
   }

   public String getEngineType(){
     return this.engineType;
   }

   public double getWeight(){
     return this.weight;
   }

   public void setWheels(int wheels){
     this.wheels = wheels;
   }

   public void setEngineType(String engineType){
     this.engineType = engineType;
   }

   public void setWeight(double weight){
     this.weight = weight;
   }
}

利用繼承,才能使用抽象類別:
public class Sedan extends Vehicle{

    private char audioClass;

    Sedan(int wheels, String engineType, double weight, char audio){
      super(wheels,engineType,weight);
      this.audioClass = audio;
    }

    //實作抽象方法
     public void ignite(){
       System.out.println("Engine start!");
    }
}

實作時,不可以實例化抽象類別:
public class Demo {
 public static void main(String[] args){

    //錯誤的範例:
    //Vehicle vo = new Vehicle(4, "Gas" , 1234.32);

    //正確的範例:
    Sedan bm = new Sedan(4, "Diesel" , 2231.21 , 'A');
    bm.ignite();
 }
}