ruby的 继承和多态
class Person
def initialize( name,age=18 )
@name = name
@age = age
@motherland = "China"
end
def talk
puts "my name is "+@name+", age is "+@age.to_s
if @motherland == "China"
puts "I am a Chinese."
else
puts "I am a foreigner."
end
end
attr_writer :motherland
end
class Student < Person
def talk
puts "I am a student. my name is "+@name+", age is "+@age.to_s
end
end
class Worker < Person
def talk
puts "I am a worker. my name is "+@name+", age is "+@age.to_s
end
end
p3=Student.new("kaichuan",25);p3.talk
p4=Student.new("Ben");p4.talk
p5=Worker.new("kaichuan",30);p5.talk
p6=Worker.new("Ben");p6.talk
Worker 类与 Student 类同样继承自 Person 类,亲缘关系是兄弟,当他们 talk
时,能准确表明自己身份,因为他们都重写了各自的 talk方法。 不同的子类继承一个父类,不仅子类和父类的行为有变异,而且子类彼此的行为也有差异,这就是多态。
用“ < ”表示 Student 类是 Person 类的子类。Person 类的一切,Student 类都能
继承。但是 Student 类重写了 talk 方法,所以我们看到了不同的运行结果。子类继
承父类的时候,除了重写方法;也可以添加一些新的方法;或是增强父类的方法(用
关键字 super指明)。
Ruby语言只支持单继承,每一个类都只能有一个直接父类。这样避免了多继承的复杂度。但同时,Ruby提供了mixin的机制可以用来实现多继承。
可以使用super关键字调用对象父类的方法,当super省略参数时,将使用当前方法的参数来进行调用。
class Base
def meth(info)
puts "This is Base #{info}"
end
end
class Derived < Base
def meth(info)
puts "This is derived #{info}"
super
end
end
obj1 = Derived.new
obj1.meth("test")
执行结果为:
This is derived test
This is Base test
如果传入的参数被修改再调用super的话,那么将会使用使用修改后的值。
class Base
def meth(info)
puts "This is Base #{info}"
end
end
class Derived < Base
def meth(info)
puts "This is derived #{info}"
info = "over"
super
end
end
obj1 = Derived.new
obj1.meth("test")
执行结果为:
This is derived test
This is Base over