A cut code from effective java, here we used a List
to obey the good practice of referring to objects by their interface.
// Good - uses interface as type
List<Subscriber> subscribers = new Vector<Subscriber>();
Assuming we had a car
interface and 2wheel
and 4wheel
were concrete subclasses.
Is it even recommended ( seems quite a yes ) to construct a list of type "car" ?
List<Car> car = new Vector<2wheel>();
instead of
List<2wheel> car = new Vector<2wheel>();
I agree with the book. Always use the interface type when possible. The only way I would use the
2wheel
or4wheel
implementations in theList
is if they contained specific methods that needed to be called that were not on the interface.For example:
If you had a
List
and the code using the list needed to call theinitiate4WheelDrive
method, then you must use the concrete implementation. This will often be determined by the calling code, but if possible stick to the interface so you can easily swap the implementation.Another note, the name
2wheel
would be an invalid name in Java since class and interface names cannot start with a number.