For example, I have a Label class where the default font color is black:
public class MyLabel{
protected int r=0;
protected int g=0;
protected int b=0;
public void setRGB(int r,int g,int b){
this.r=r;
this.g=g;
this.b=b;
}
}
and a subclass where the default color changes to white:
public class MySpecialLabel extends MyLabel{
public MySpecialLabel(){
this.r=255;
this.g=255;
this.b=255;
}
}
Does this violate the Liskov Substitution Principle? On one hand, the base class doesn't limit the value of rgb and rgb can change during the lifetime of the object, hence the preconditions and invariant rules don't apply. The Liskov Substitution Principle doesn't limit the constructor, so it seems this doesn't violate the Liskov Substitution Principle. On other hand, if some clients rely on the default value of MyLabel,eg:
this.setBgColor(Color.WHITE);
MyLabel label=new MyLabel();
this.addChild(label);
then replacing new MyLabel()
with new MySpecialLabel()
would make the label invisible, because they have the same color, requiring to add an extra line label.setColor(0,0,0)
to fix it:
this.setBgColor(Color.WHITE);
MyLabel label=new MySpecialLabel();
label.setColor(0,0,0);
this.addChild(label);
It seems MyLabel cannot be replaced by MySpecialLabel without any adaption. So I don't know whether it is violating Liskov Substitution Principle, or not.
MyLabel
contract that promises a specific color value, so it can't possibly violate something that was never promised in the first place, can it?