我认为Ruby除了mixin之外只允许单继承.但是,当我有Square
继承类的类时Thing
,默认Thing
继承Object
.
class Thing
end
class Square < Thing
end
Run Code Online (Sandbox Code Playgroud)
这不代表多重继承吗?
saw*_*awa 70
我认为你正在以错误的方式理解多重继承的含义.可能你想到的是多重继承是这样的:
class A inherits class B
class B inherits class C
Run Code Online (Sandbox Code Playgroud)
如果是这样,那就错了.这不是多重继承的原因,Ruby也没有问题.多重继承的真正含义是:
class A inherits class B
class A inherits class C
Run Code Online (Sandbox Code Playgroud)
你肯定不能用Ruby做到这一点.
Ism*_*reu 28
不,多继承意味着一个类有多个父类.例如,在ruby中,您可以使用以下模块执行此操作:
class Thing
include MathFunctions
include Taggable
include Persistence
end
Run Code Online (Sandbox Code Playgroud)
所以在这个例子中,Thing类将有一些来自MathFunctions模块,Taggable和Persistence的方法,使用简单的类继承是不可能的.
Nit*_*esh 11
如果B类继承自A类,则B的实例具有A类和B类行为
class A
end
class B < A
attr_accessor :editor
end
Run Code Online (Sandbox Code Playgroud)
Ruby具有单一继承,即每个类只有一个父类.Ruby可以使用模块(MIXIN)模拟多重继承
module A
def a1
end
def a2
end
end
module B
def b1
end
def b2
end
end
class Sample
include A
include B
def s1
end
end
samp=Sample.new
samp.a1
samp.a2
samp.b1
samp.b2
samp.s1
Run Code Online (Sandbox Code Playgroud)
模块A由方法a1和a2组成.模块B由方法b1和b2组成.类Sample包括模块A和B.类Sample可以访问所有四种方法,即a1,a2,b1和b2.因此,您可以看到类Sample继承自两个模块.因此,您可以说类Sample显示多重继承或mixin.
多重继承 - 这在ruby中绝对不可能,甚至模块都没有.
多级继承 - 即使使用模块,这也是可能的.
为什么?
模块充当包含它们的类的绝对超类.
例1:
class A
end
class B < A
end
Run Code Online (Sandbox Code Playgroud)
这是一个普通的继承链,你可以通过祖先来检查它.
B.ancestors => B - > A - >对象 - > ..
模块继承 -
例2:
module B
end
class A
include B
end
Run Code Online (Sandbox Code Playgroud)
上面例子的继承链 -
B.ancestors => B - > A - >对象 - > ..
这与Ex1完全相同.这意味着模块B中的所有方法都可以覆盖A中的方法,并且它充当真正的类继承.
例3:
module B
def name
p "this is B"
end
end
module C
def name
p "this is C"
end
end
class A
include B
include C
end
Run Code Online (Sandbox Code Playgroud)
A.ancestors => A - > C - > B - >对象 - > ..
如果你看到最后一个例子,即使包含两个不同的模块,它们也在一个继承链中,其中B是C的超类,C是A的超类.
所以,
A.new.name => "this is C"
Run Code Online (Sandbox Code Playgroud)
如果从模块C中删除name方法,则上面的代码将返回"this is B".这与继承一个类相同.
所以,
在任何时候,ruby中只有一个多级继承链,它会使该类具有多个直接父级.