Page 1 of 1

[HD Pg 0, Sec. 12.7.0 - exercise]

Posted: Mon Nov 30, 2020 7:37 pm
by sinosuke11
Hi.

This is the code encompassing the exercises of chapter 12,

Code: Select all

package begin010;

import java.util.ArrayList;
import java.util.List;

public class TestClass {
//Main ***********************************************
	public static void main(String[] args) {

		Vehicle b = new Car();
		Vehicle c = new Truck();
		System.out.println(c.getFeature("width"));
		System.out.println(b.getFeature("bumper"));
		b.start();
		c.start();

	}
}
// Interfaces ****************************************

interface Drivable {

	final List<String> features = new ArrayList<String>();

	void drive();

	void start();

}

interface VehicleHelper {

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

// Abstract class  **********************************

abstract class Vehicle implements Drivable, VehicleHelper {

	protected static int VIN;

	private String make;
	private String model;
	int vin = VIN;

	static {
		VIN = 0;

		features.add("heigth");
		features.add("width");
		features.add("length");
		features.add("power");
		features.add("boot capacity");

	}

	public Vehicle() {
		vin = VIN++;
		VehicleHelper.register(this);
	}

	public String getMakeAndModel() {
		return this.make + "    " + this.model;
	}

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

	public String getFeature(String featureName) {
		return (features.contains(featureName)) ? "This vehicle has this feature." : "N. A";

	}

}

// Classes **********************************************

class Car extends Vehicle {

	@Override
	public void drive() {

	}

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

	}

}

class Truck extends Vehicle {

	@Override
	public void drive() {

	}

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

}
I would appreciate if you would take a look to see if the code follow the requirements and what could be improved.
In abstract classes is it better instance initializers or constructors?
Thanks

Re: [HD Pg 0, Sec. 12.7.0 - exercise]

Posted: Wed Dec 02, 2020 6:38 am
by admin
1. Why do you need Vehicle to implement VehicleHelper?
2. I am not convinced with the getFeature requirement (Q7) implementation in your example. Ideally, invoking getFeature() on any Vehicle instance should produce a value that is unique for that Vehicle, if that Vehicle supports that feature. That is not happening in your code.

Rest looks great!
Paul.