开发者

Does Ruby support inclusion polymorphism

Does Ruby support "inclusion polymorphism"? Is this the same as Duck Typing?

If not, what is the difference between polymorphism and duck-typing in Ruby?

Can someone please illustrate with my example below:

# superclass - inheritance
class Animal
  def make_noise
    # define abstarct method (force override)
    raise NoMethodError, "default make_noise method called"
  end
end

# module - composition
module Fur
  def keep_warm
    # etc
  end
end

# subclass = is-a relationship
class Bird < Animal
  # override method - polymorphism
  def make_noise
    "Kaaw"
  end
end

class Cat < Animal
  # module mixin = has-a relationship
  include Fur

  def make_noise
    "Meow"
  end
end

class Radio
  # duck typing (no inheritance involved)
  def make_noise
    "This is the news"
  end
end

class Coat
  include Fur
end

animals = [Bird,Cat,Radio,Coat,Animal]

animals.each do |a|
  # polymorphism or duck typing?
  obj = a.new
  if obj.respond_to? 'make_noise'
    puts obj.make开发者_如何学运维_noise
  end
end


Well in your example, you could say that the each loop works thanks to duck typing (related to the fact that the client code only cares if the variable can make noise), but the fact that Cats and Birds can make noise is a theoretycal description of the subclassing mechanism known as polymorphism.

So you could say that a difference between polymorphism and duck typing is that polymorphism is the idea that you can use an object that claims to be a certain type in place of another in any circumstances, but duck typing is the idea that you don't care about the type of the object, as long as it implements certain interface. So for instance in Java, if you make a subclass of Animal, you can expect it not only to make noise, but also to have other behaviour associated to animals, while in the case of Ruby, the fact that an object can make noise doesn't depend on the type, just on the existence of a particular method. Of course in Java you have the concept of interfaces that give a (static) mechanism for the same pattern.

The most important difference IMHO is different programming philosophies behind the names, not so much in the concepts themselves.

I guess it all comes down to the fact that the term polymorfism is associated with more structured OOP ideas, while Ruby had to invent a name for a way of programming which has different posibilities and implications.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜