I agree with the book. Always use the interface type when possible. The only way I would use the 2wheel
or 4wheel
implementations in the List
is if they contained specific methods that needed to be called that were not on the interface.
For example:
public interface Car{
public void drive();
}
public class 2wheel implements Car{
public void drive(){
//implementation
}
}
public class 4wheel implements Car{
public void drive(){
//implementation
}
public void initiate4WheelDrive(){
//implementation
}
}
If you had a List
and the code using the list needed to call the initiate4WheelDrive
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.