How is polymorphism defined in Java?
I understand this:
Polymorphism needs to be implemented by means of interfaces, that is, all classes that implement this particular interface are like him.
What is duck type?
This is defined in programming Ruby: If an object can walk like a duck and croak like a duck, then the interpreter will gladly treat it as a duck. (Programming Ruby Chinese version P367)
One day I asked a colleague if there was a polymorphism in Ruby.
Get an interesting answer: weak type of dynamic language, no abstract class, no interface, you say there is no polymorphism?
Polymorphism is very useful, polymorphism is not only static object-oriented language such as java/c# and so on? Of course not, one of the three characteristics of the polymorphic oo language.
Ruby is a purely object-oriented language, and Ruby is of course polymorphic. Ruby's Polymorphic property is its duck type.
Don't say much, put code
Ruby Code
class SimpleFilter
attr_reader :fltr_expres
def initialize(fltr_expres)
@fltr_expres = fltr_expres
end
def apply_filter(value)
value.include?(@fltr_expres)
end
end
class RegexFilter
attr_reader :fltr_expres
def initialize(fltr_exprs)
@fltr_expres = fltr_exprs
end
def apply_filter(value)
value =~ @fltr_expres
end
end
# SimpleFilter和RegexFilter这两个类并不共享一个基类
# 在单元测试中对两个类的实例组成的集合进行迭带
# 简单的调用同名的"apply_filter()"方法就轻松实现了多态
# ruby没有接口,只要方法名匹配,就能轻松的实现了多态特性
require 'test/unit'
class FilterTest < Test::Unit::TestCase
def test_filters
fltrs = [SimpleFilter.new('oo'), RegexFilter.new(/Go+gle/)]
fltrs.each do |fltr|
assert(fltr.apply_filter('I love to Google'))
end
end
end
In Ruby, class is never (almost never) a type, whereas an object type is based on what the object can do, that is, the object's behavior (method).