Page 1 of 1

[HD-OCP17/21-Fundamentals Pg 0, Sec. 13.7.0 - exercise]

Posted: Sun Dec 01, 2024 10:55 am
by joaoclopes
Hello! Regarding the exercise is this a good solution?

Code: Select all

public interface Drivable {

    void drive();

    default void start() {
        System.out.println("Starting...");
    }
}


public interface VehicleHelper {

    static void register(Vehicle v) {
        System.out.println(v.getVIN());
    }
}


import java.util.List;

public abstract class Vehicle implements Drivable {

    private final String make;
    private final String model;
    private final String vin;
    private final List<String> features;

    public Vehicle(String make, String model, String vin, List<String> features) {
        this.make = make;
        this.model = model;
        this.vin = vin;
        this.features = features;
        VehicleHelper.register(this);
        start();
    }

    public String getMakeAndModel() {
        return "%s and %s".formatted(make, model);
    }

    public final String getVIN() {
        return this.vin;
    }

    public final String getFeature(String feature) {
        for (String f : features) {
            if (f.equals(feature)) {
                return feature;
            }
        }
        return "N.A";
    }

}


import java.util.List;

public class Car extends Vehicle {

    public Car(String make, String model, String vin) {
        super(make, model, vin, List.of("height"));
    }

    @Override
    public void drive() {
        System.out.println("drive car");
    }

    @Override
    public void start() {
        System.out.println("Starting car");
    }
}


public class ToyCar extends Car {

    public ToyCar() {
        super("toy", "toy", "12345");
    }
}


import java.util.List;

public class Truck extends Vehicle {

    public Truck(String make, String model, String vin) {
        super(make, model, vin, List.of("power"));
    }

    @Override
    public void drive() {
        System.out.println("Drive Truck");
    }

    @Override
    public void start() {
        System.out.println("Starting truck");
    }
}
Thanks!

Re: [HD-OCP17/21-Fundamentals Pg 0, Sec. 13.7.0 - exercise]

Posted: Mon Dec 02, 2024 11:42 pm
by admin
Yes, this looks good :thumbup: