我读过一些关于让 Square 成为 Rectangle 类的继承类是一种不好的做法的文章,说它违反了 LSP(Liskov 替换原则)。我还是不明白,我在Ruby中做了一个示例代码:
class Rectangle
attr_accessor :width, :height
def initialize(width, height)
@width = width
@height = height
end
end
class Square < Rectangle
def initialize(length)
super(length, length)
end
def width=(number)
super(number)
@height = number
end
def height=(number)
super(number)
@width = number
end
end
s = Square.new(100)
s.width = 50
puts s.height
谁能告诉我它有什么问题?