[HD Pg 0, Sec. 12.7.0 - exercise]

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
sinosuke11
Posts: 1
Joined: Mon Nov 09, 2020 10:24 am
Contact:

[HD Pg 0, Sec. 12.7.0 - exercise]

Post 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

admin
Site Admin
Posts: 10386
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post 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.

Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 8 guests