Created
February 17, 2018 17:28
-
-
Save laidback/8aedf0846159f89c3242bddc3f7f1db9 to your computer and use it in GitHub Desktop.
java_cars_detail created by laidback - https://repl.it/@laidback/javacarsdetail
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| interface SubSystem { | |
| public void startSystem(); | |
| public void stopSystem(); | |
| public SubSystemState getState(); | |
| } | |
| interface SubSystemState {} | |
| enum Color { WHITE, BLACK, RED, BLUE, GREEN; } | |
| enum EngineType { DIESEL, GASOLINE; } | |
| enum EngineState implements SubSystemState { ON, OFF; } | |
| class Engine implements SubSystem { | |
| private EngineType type; | |
| private EngineState state; | |
| public Engine(EngineType type) { | |
| this.type = type; | |
| } | |
| public void startSystem() { | |
| this.state = EngineState.ON; | |
| } | |
| public void stopSystem() { | |
| this.state = EngineState.OFF; | |
| } | |
| public EngineState getState() { | |
| return this.state; | |
| } | |
| } | |
| class Car implements SubSystem { | |
| Color color; | |
| Engine engine; | |
| int milage = 0; | |
| public Car(Color color, Engine engine) { | |
| this.color = color; | |
| this.engine = engine; | |
| } | |
| public void startSystem() { | |
| this.engine.startSystem(); | |
| } | |
| public void stopSystem() { | |
| this.engine.stopSystem(); | |
| } | |
| public SubSystemState getState() { | |
| return this.engine.getState(); | |
| } | |
| public void drive(int miles) { | |
| if (this.engine.getState() == EngineState.OFF) { | |
| } else { | |
| this.milage += miles; | |
| } | |
| } | |
| public int getMilage() { | |
| return this.milage; | |
| } | |
| /** | |
| * Static method can be used without an instance, e.g. to convert between measure systems | |
| */ | |
| public static int milesToKilometers(int miles) { | |
| return miles * 2; | |
| } | |
| public void printStatus() { | |
| // Use the static method of String to create a formated String | |
| String status = String.format("Car: %s, Engine: %s, Milage: %s", this.color, this.engine.getState(), this.milage); | |
| System.out.println(status); | |
| } | |
| } | |
| class Main { | |
| public static void main(String[] args) { | |
| // Using an engine | |
| System.out.println("Hello Engine!"); | |
| Engine engine = new Engine(EngineType.GASOLINE); | |
| Color color = Color.BLACK; | |
| Car car = new Car(color, engine); | |
| car.printStatus(); | |
| car.startSystem(); | |
| car.drive(50); | |
| car.stopSystem(); | |
| car.printStatus(); | |
| car.drive(50); | |
| car.printStatus(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment