Alan Alan - 12 days ago 7
Java Question

Best way to structure a class hierarchy?

I'm attempting a challenge that is based around the structure of a class hierarchy. I must try to evaluate and correctly structure a hierarchy that includes transportation-based vehicles. Here are the class options:


  • Bicycle

  • Car

  • Cycle

  • JetPlane

  • RoadVehicle

  • Refuelable

  • Train

  • Transport

  • Tricycle



In terms of structure, I must decide which classes are abstract, which classes extends which and which classes are interfaces.

Here is what I have come up with so far:

Transport

public abstract class Transport
{

//Super class. All vehicles are a form of transportation.

}


Bicycle

public abstract class Bicycle extends RoadVehicle
{

//Bicycle is a road vehicle. Does not implement Refuelable as it does not use fuel. Is abstract because Cycle is its sub-class.

}


Car

public class Car extends RoadVehicle implements Refuelable
{

//Extends RoadVehicle which extends Transport and also implements Refuelable as it uses fuel.

}


Cycle

public class Cycle extends Bicycle
{

//Cycle is an act which is carried out when using a Bicycle so it extends Bicycle.

}


JetPlane

public class JetPlane extends Transport implements Refuelable
{

//JetPlane is not a road vehicle but directly extends Transport because it is used as a form of transport, also implements Refuelable.

}


RoadVehicle

public abstract class RoadVehicle extends Transport
{

//All classs that are road vehicles extends this clss. This seperates the road vehicles from the non-road vehicles.

}


Refuelable

public interface Refuelable
{

//An interface that declares which tyypes of transport use fuel and which do not.

}


Train

public class Train extends Transport implements Refuelable
{

//Trains are not a road veicle but do extend Transport and are refuelable.

}


Tricycle

public class Tricycle extends Transport
{

//Tricycle is a form of transport for children, it is not refuelable and does not operate on the road.

}


Is this right or can you see any errors? I'm doing this to test my knowledge on inheritance so any advice or pointers wold be much appreciated, thanks.

Answer

Given that we can't tell the methods that are supposed to be in each entity, I would start with the following:

interface Transport
interface Refuelable
interface RoadVehicle extends Transport
interface Cycle extends RoadVehicle

class Bicycle implements Cycle
class Tricycle implements Cycle
class Car implements RoadVehicle, Refuelable
class JetPlane implements Transport, Refuelable
class Train implements Transport