I read some posts about "composition over inheritance","where to use composition/inheritance" , "Is-a relationship..." or "Liskov substitution principle" for some time, but I am not sure if I get the right idea about "composition over inheritance".
Alternatively, in my experience, it seems just one simple golden rule to check if we should use composition or inheritance:
If a parent class never appears in my codes except in its child class, it should be composition instead of inheritance
for example, suppose I have a parent class Fruit:
public class Fruit{
public String printName(){
System.out.println("Fruit");
}
}
and child class Orange:
public class Orange extends Fruit{
public String printName(){
System.out.println("Orange");
}
}
and Grape:
public class Grape extends Fruit{
public String printName(){
System.out.println("Grape");
}
}
If I really needs inheritance, in my source code there should be something like
Vector<Fruit> fruitList;
,
Fruit fruit=new Orange();
or
((Fruit)f).printName();
which needs "Fruit" to compile, so not counting Orange and Grape (child class),if my source codes never have "Fruit", or if my codes can compile without "Fruit", then Orange and Grape should not be extended from "Fruit" and hence misusing inheritance, it that true?