Sometimes there is no doubt, but sometimes it can be a very hard decision. Let me show you a couple of examples:
Inheritance:
public class Employee{
public void goToWork(){
//...
}
}
public class Lawyer extends Employee{
//private Employee body;
/*public void goToWork(){
body.goToWork(); // Does that make any sense?
}*/
}
Delegation:
public class Lights{
public void turnOn(){
//...
}
}
public class Car{ //public class Car extends Lights? Nice car then...
private Lights light;
public void turnOnLights(){
light.turnOn();
}
}
Which one?
public class Field{
public void grow(Seeds s){
//...
}
}
public class Plantation{ //extends Field{ makes sense too
private Field field;
private Worker[] workers;
private Vehicle[] tractors;
public void grow(Seeds s){
//...
field.grow(s);
}
}
So, are there any tips that can help to choose between inheritance and delegation when both are acceptable and each one has their own advantages and disadvantages? Is the choice random and totally based on programmer's mood?