我讀過一些關於使Square成爲Rectangle類的繼承類的做法的文章,這是一種不好的做法,稱它違反了LSP(Liskov替代原則)。我仍然不明白,我在Ruby中做了一個示例代碼:Square和Rectangle繼承有什麼問題?
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
有人能告訴我它有什麼問題嗎?
塊狀太空公主? http://www.youtube.com/watch?v=pJTrD3R5cj0 – paxdiablo
哇,這很有趣,但我不太明白 – mko
yozloy,道歉,我只是提出一點,你可能想解釋你的意思LSP,以便那些不知道它的人不必搜索。 – paxdiablo