Buonasera ragazzi,
volevo fare una domanda riguardo al principio di sostituzione di Liskov, il quale ci dice deve essere rispettata la sostitutività dei tipi derivati rispetto ai tipi base.
Il classico esempio del rettangolo e del quadrato, dove il quadrato è visto come specializzazione di rettangolo.
Qualora andassi a fare:codice:class Rectangle { protected int m_width; protected int m_height; public void setWidth(int width){ m_width = width; } public void setHeight(int height){ m_height = height; } public int getWidth(){ return m_width; } public int getHeight(){ return m_height; } public int getArea(){ return m_width * m_height; } } class Square extends Rectangle { public void setWidth(int width){ m_width = width; m_height = width; } public void setHeight(int height){ m_width = height; m_height = height; } } }
codice:class LspTest { private static Rectangle getNewRectangle() { // it can be an object returned by some factory ... return new Square(); } public static void main (String args[]) { Rectangle r = LspTest.getNewRectangle(); r.setWidth(5); r.setHeight(10); // user knows that r it's a rectangle. // It assumes that he's able to set the width and height as for the base class System.out.println(r.getArea()); // now he's surprised to see that the area is 100 instead of 50. } }
"Crediamo" di avere a che fare con un rettangolo ma alla fine ci ritroviamo che l'area del rettangolo avente base 5 e altezza 10 è uguale a 100 anzichè 50.
Volevo capire come si risolve, qual è la soluzione riguardo al principio di sostituzione di Liskov.
Nell'esempio si fà override dei metodi setWeight e setHeight, e alla fine esce fuori un macello poichè non viene rispettata la sostitutività dei tipi derivati.