2015年9月23日 星期三

Composition Implementation

Composition 實作範例:
public interface Car {
    public void start();
}

public abstract class BasicCar {
    public abstract void start();
}

public class Diesel extends BasicCar{
    public void start(){
        System.out.println("Diesel Start....");
    }
}

public class Mobile extends BasicCar{
    public void ignite(){
        System.out.println("Power turn on ...");
    }

    @Override
    public void start() {
        this.ignite();
    }
}

public class Hybrid  implements Car{
    private Diesel die = new Diesel();
    private Mobile m1 = new Mobile();
    
    public void start(){
        die.start();
        m1.ignite();
    }   
}

public class Racing extends Hybrid{
    public void start(){
        super.start();
        System.out.println("Engine is starting.....");
    }
}

public class Demo {
    public static void main(String[] args){
    
        Racing r1 = new Racing();
        r1.start();
    }
}