[HD Pg 0, Sec. 12.7.0 - exercise]
Posted: Mon Nov 30, 2020 7:37 pm
Hi.
This is the code encompassing the exercises of chapter 12,
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
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");
}
}
In abstract classes is it better instance initializers or constructors?
Thanks