I have 3 classes (Car (superclass), CarToRent, and CarToSell (extend Car).
I'm making an interface (CarCompany) and want to store an ArrayList
of type car in it. How do I do this? Please help?
I have 3 classes (Car (superclass), CarToRent, and CarToSell (extend Car).
I'm making an interface (CarCompany) and want to store an ArrayList
of type car in it. How do I do this? Please help?
In an interface, you can't set attributes because all of them have the final modifier by default, so just declare the get
and set
method for your interface. Let that the implementors have the attribute and overrides those methods.
public interface CarCompany {
List<? extends Car> getCarList();
void setCarList(List<? extends Car> carList);
}
UPDATE:
First, you shouldn't use ArrayList
even if you can, instead use List
interface, ArrayList
implements that interface (more info about this: What does it mean to "program to an interface"?):
List<Car> carList = new ArrayList<Car>();
Second, if you have a superclass, the list attribute shouldn't be for the superclass, instead for a template that supports all that class generation. Let's see a sample of this: you have a DAO class that returns a List<CarToRent>
and a List<CarToSell>
in different methods. Later on, in a business class, you need to read all the elements for a List<Car>
and use the price
of the car for some formula. Will you create a method to convert from List<CarToRent>
to List<Car>
and one for List<CarToSell>
to List<Car>
, what if later on you need to create a new child of Car
like WreckedCar
for a CarWorkshop
, will you create a third converter? So, instead of all that pain, you can use the List<? extends Car>
that do that "dirty work" for you:
public void executeSomeFormula(List<? extends Car> carList) {
//getting the actual VAT value (just for a sample);
double actualVAT = getActualVATValue();
//every object in the list extends Car, so it can be threatened as a Car instance
for(Car car : carList) {
car.setTotalPrice(car.getPrice() * (1 + actualVAT));
}
}
You should create an ArrayList<CarCompany>
to be able to store every kind of object which comes from a class that implements your CarCompany
interface.
import java.util.ArrayList;
ArrayList<TYPE> al = new ArrayList<TYPE>();
so if you need CarCompany
eg.
ArrayList<CarCompany> al = new ArrayList<CarCompany>();
Also have a look at this document about Class ArrayList
Your interface
should not have a List
of cars. It may define getter and setting methods for the List
but should not define it. Your concrete classes that implement your interface should define the List
.
public class CarCompany{
private List<Car> myList = new ArrayList<Car>();
}