I'm trying to get to grips with inheritance. I have a class structure that consists of an interface (Aeroplane), an abstract class(Aeroplane implementation) which implements methods consistent with both classes, and two subclasses: a passenger jet, and a jumbo jet.
passenger and jumbo jet each have a different fuel capacity and hence contain the following field:
private static final int MAX_FUEL_CAPACITY = 49;
I wrote a method addFuel, which enforces certain restrictions:
I originally had the following in each class, but thought it bad practice because there's a lot of duplication:
Integer addFuel(int litres) {
if (litres < 1) {
throw IndexOutOfBoundsException("entered fuel volume must be greater than zero. Zero litres entered.")
}
if (fuelInLitres == MAX_TANK_CAPACITY) {
throw IndexOutOfBoundsException("tank is at full capacity. Zero litres entered.")
}
if (litres + fuelInLitres > MAX_TANK_CAPACITY) {
throw IndexOutOfBoundsException("entered fuel volume is too large - tank does not have sufficient capacity. Zero litres entered.")
}
fuelInLitres += litres;
}
So I ended up with the following in my abstract class:
Integer addFuel(int litres) {
if (litres < 1) {
throw IndexOutOfBoundsException("entered fuel volume must be greater than zero. Zero litres entered.")
}
}
And this in each subclass, but I can't see that's right either?
Integer addFuel(int litres) {
super.addFuel(litres)
if (fuelInLitres == MAX_TANK_CAPACITY) {
throw IndexOutOfBoundsException("tank is at full capacity. Zero litres entered.")
}
if (litres + fuelInLitres > MAX_TANK_CAPACITY) {
throw IndexOutOfBoundsException("entered fuel volume is too large - tank does not have sufficient capacity. Zero litres entered.")
}
fuelInLitres += litres;
}