//LiskovSubstitutionPrincipleViolated.java
//Illustrates a violation of Liskov's Substitution Principle, for
//which see the Wikipedia description quoted at the end of this
//file. Bottom line ... be careful when you extend a class that
//the derived class really does satisfy the "is a" relationship.

class Rectangle
{
    protected int width;
    protected int height;

    public void setWidth(int width)
    {
        this.width = width;
    }

    public void setHeight(int height)
    {
        this.height = height;
    }

    public int getWidth()
    {
        return width;
    }

    public int getHeight()
    {
        return height;
    }

    public int getArea()
    {
        return width * height;
    }
}

class Square extends Rectangle
{
    public void setWidth(int width)
    {
        this.width = width;
        this.height = width;
    }

    public void setHeight(int height)
    {
        this.width = height;
        this.height = height;
    }
}

class LiskovSubstitutionPrincipleViolated
{
    private static Rectangle getNewRectangle()
    {
        return new Square();
    }

    public static void main(String args[])
    {
        Rectangle r = LiskovSubstitutionPrincipleViolated.getNewRectangle();

        r.setWidth(5);
        r.setHeight(10);
        //User knows that r is a rectangle.
        //So he assumes he can set width and height as for the base class.

        System.out.println(r.getArea());
        //But now he's surprised to see that the area is 100 instead of 50.
    }
}

/*
    In Java, S is a subtype of T if S extends or implements T.

    The (Liskov) Substitution Principle
    A variable of a given type may be assigned a value of any subtype, and a
    method with a parameter of a given type may be invoked with an argument
    of any subtype of that type.

    Further explanation ...
    Substitutability is a principle in object-oriented programming that states
    that, in a computer program, if S is a subtype of T, then objects of type
    T may be replaced with objects of type S (i.e., an object of the type T
    may be substituted with its subtype object of the type S) without altering
    any of the desirable properties of that program (correctness, task
    performed, etc.). More formally, the Liskov substitution principle (LSP)
    is a particular definition of a subtyping relation, called (strong)
    behavioral subtyping, that was initially introduced by Barbara Liskov in
    a 1987 conference keynote address entitled Data Abstraction and Hierarchy.
    It is a semantic rather than merely a syntactic relation because it
    intends to guarantee semantic interoperability of types in a hierarchy,
    object types in particular. Barbara Liskov and Jeannette Wing formulated
    the principle succinctly in a 1994 paper as follows:

    Subtype Requirement:
    Let p(x) be a property provable about objects x of type T. Then p(y) should
    be true for objects y of type S where S is a subtype of T.
*/

