Is it possible to store different objects that have been extended from the same abstract object in a single container and be able to access all of the custom fields of those objects. Let me present an example:
Suppose I have two cars: ford and honda. Since all cars have weight and color, I could make the following abstract class:
public abstract class Car{
private double weight;
private String color;
public Car(){
this.weight=0;
this.color="";
}
...getters and
...setters
}
Now suppose my Ford class has an additional field ‘radio‘ and looks like this:
public Ford extends Car(){
private String radio;
public Ford(){
super();
this.radio = "generic";
}
}
Similarly, the Honda class has a custom field ‘camera‘
public Honda extends Car(){
private String camera;
public Honda(){
super();
this.camera= "analog";
}
}
Is it possible to keep the instances of these classes in a single container, something like the following below. Please note the code below works but this is not quite what I want. see comments below:
Ford ford = new Ford();
Honda honda = new Honda();
ArrayList<Car> myCars = new ArrayList<Car>();
myCars.add(ford);
myCars.add(honda);
HERE IS MY PROBLEM:
When I do myCars.get(0) I get an object of class Car (obviously) and am never able to get the custom field radio. Of course I could do something like ((Ford) myCars.get(0)) and will be able to see the radio field, but is it possible to create a better container what would reveal all of the fields without downcasting etc, something like:
myContainer.get(0) – would return the Ford class and I would have an access to weight, color and radio
myContainer.get(1) – would return the Honda class and I would have an access to weight, color and camera.
My hunch tells me that the solution is near and it is possible, but my expertise in Java is not up there yet. Maybe I have do to some sort of generics or hashmaps??
Thank you guys!!
There are several alternatives, none of which perfectly meets your ideal.
Carclass and either returnNullor throw an exception where they are not applicable.CarContainerclass that wraps your list and has methods that return all the elements of a specific type, e.g.List<Ford> getAllTheFords(). In this way you can hide the ugly casts in your container class.I listed alternatives according to my personal preference 🙂