To show polymorphism and duck-typing are 2 different animals :), I add
more code and comment in the above example. Pay attention to the Radio.
#=================
class Animal
attr_reader :name
def initialize(name)
@name= name
end
def says
@name + " says some strange grunty sound"
end
end
class Dog < Animal
def says
@name + " says Woof!"
end
end
class Cat < Animal
attr_reader :name
def says
@name + " says News"
end
end
# Attention: Radio is not an Animal
class Radio
attr_reader :name
def initialize(name)
@name= name
end
def says
@name + " says News"
end
end
animal = Dog.new("Fido")
puts animal.says
animal = Cat.new("Socks")
puts animal.says
animal = Animal.new("Suzi")
puts animal.says
# here animal is not an Animal any more!!!
# It will not compile in C++/Java
# It is fine, since ruby duck/dynamic typing
animal = Radio.new("BBC")
puts animal.says
#=================
--
Posted via http://www.ruby-forum.com/.