什麼是遺傳
方法是繼承的
class A
def boo; p 'boo' end
end
class B < A; end
b = B.new
b.boo # => 'boo'
類方法是繼承的
class A
def self.boo; p 'boo' end
end
class B < A; end
p B.boo # => 'boo'
常量是繼承的
class A
WOO = 1
end
class B < A; end
p B::WOO # => 1
但要注意,它們可以被覆蓋:
class B
WOO = WOO + 1
end
p B::WOO # => 2
例項變數是繼承的:
class A
attr_accessor :ho
def initialize
@ho = 'haha'
end
end
class B < A; end
b = B.new
p b.ho # => 'haha'
請注意,如果你覆蓋初始化例項變數而不呼叫 super
的方法,它們將為零。從上面繼續:
class C < A
def initialize; end
end
c = C.new
p c.ho # => nil
類例項變數不會被繼承:
class A
@foo = 'foo'
class << self
attr_accessor :foo
end
end
class B < A; end
p B.foo # => nil
# The accessor is inherited, since it is a class method
#
B.foo = 'fob' # possible
類變數並不是真正繼承的
它們在基類和所有子類之間共享為 1 個變數:
class A
@@foo = 0
def initialize
@@foo += 1
p @@foo
end
end
class B < A;end
a = A.new # => 1
b = B.new # => 2
從上面繼續:
class C < A
def initialize
@@foo = -10
p @@foo
end
end
a = C.new # => -10
b = B.new # => -9