I am having trouble deciding between these three ways to handle field variables for a subclass and superclass.
Method 1:
public abstract class Vehicle {
public abstract int getNumberOfWheels();
public abstract int getCost();
}
public class Car extends Vehicle {
private int numberOfWheels;
private int cost;
public Car() {
this.numberOfWheels = 4;
this.cost = 10000;
}
public int getNumberOfWheels() {
return numberOfWheels;
}
public int getCost() {
return cost;
}
}
With this method i have to implement the same duplicate getter methods in every subclass of Vehicle. I imagine this would be a problem with more complicated getter method, that have to be duplicated and eventually maintained.
Method 2:
public abstract class Vehicle {
private int numberOfWheels;
private int cost;
public int getNumberOfWheels() {
return numberOfWheels;
}
public int getCost() {
return cost;
}
public void setNumberOfWheels(int numberOfWheels) {
this.numberOfWheels = numberOfWheels;
}
public void setCost(int cost) {
this.cost = cost;
}
}
public class Car extends Vehicle {
private int numberOfWheels;
private int cost;
public Car() {
super.setNumberOfWheels(4);
super.setCost(10000);
}
}
With this method i have to implement setter methods that i might not want to have. I might not want other classes to be able to change the fields, even in the same package.
Method 3:
public abstract class Vehicle {
private int numberOfWheels;
private int cost;
public class Vehicle(int numberOfWheels, int cost) {
this.numberOfWheels = numberOfWheels;
this.cost = cost;
}
public int getNumberOfWheels() {
return numberOfWheels;
}
public int getCost() {
return cost;
}
}
public class Car extends Vehicle {
private int numberOfWheels;
private int cost;
public Car() {
super(4, 10000);
}
}
With this method and with a lot of fields, the amount of constructor parameters will grow huge, which just feels wrong.
It seems like this would be a common enough problem for there to exist some kind of "best practice". Is there a best way to do this?