Inheritance logic problem
Hello, ive got a few classes, Bus, Car, Train, and Truck, they all inherit from the class Vehicle.
the Vehicle class contains members and methods which are common to all the subclasses like, type of vehicle(bus, car, train, truck), weight, price, owner, registration number and so on...
the problem im having is with accessing the subclasses methods in main(), for example, one of the subclasses "Bus" contains its own members like Number of Seats, and Company Name, and they have set and get methods, .
When I try to access or change the value of the NumberOfSeats or CompanyName, i do this in the main:
Code:
List<Vehicle> vehicleList = new ArrayList<Vehicle>();
vehicleList.add(new Bus());
vehicleList.add(new Truck());
vehicleList.add(new Train());
((Bus)veh).setCompanyName(); /* setCompanyName doesnt belong to the Vehicle class */
// is there a way I could just do
vehicleList.get(0).setCompanyName()
;
In alot of cases im finding myself doing this...
Code:
String subclassType = vehicleList.get(0).getVehicleType(); /* returns either Bus, Car, Train or Truck as a string */
if(subclassType.equals("Truck")){
((Truck)veh).SomeTruckOnlyMethod();
}else if(subclassType.equals("Bus")){
((Bus)veh).someBussOnlyMethod();
}
Is there a better way to do this? because it looks really messy with so many If statements because i have alot of subclasses which inherit from Vehicle, also I didnt really want all those subclasses methods to be in the super class so access them because alot of the subclasses dont need them, like companyName which is only for the Bus.
Sorry for the long post, also ignore any syntax errors in the above code, i jsut typed that up in here to show you the basic way ive done it.