What is Interface Duck Typing?

后端 未结 5 1547
深忆病人
深忆病人 2020-12-08 07:29

I heard the word Interface Duck Typing, but do not understand at all what is it? So I read a wiki about this and they said:

In computer programming wi

5条回答
  •  独厮守ぢ
    2020-12-08 07:57

    Duck typing allows an object to be passed in to a method that expects a certain type even if it doesn’t inherit from that type. All it has to do is support the methods and properties of the expected type in use by the method. I emphasize that last phrase for a reason. Suppose we have a method that takes in a duck instance, and another method that takes in a rabbit instance. In a dynamically typed language that supports duck typing, I can pass in my object to the first method as long as my object supports the methods and properties of duck in use by that method. Likewise, I can pass my object into the second method as long as it supports the methods and properties of rabbit called by the second method. Is my object a duck or is it a rabbit? Like the above image, it’s neither and it’s both. In many (if not most) dynamic languages, my object does not have to support all methods and properties of duck to be passed into a method that expects a duck. Same goes for a method that expects a rabbit.It only needs to support the methods and properties of the expected type that are actually called by the method.

    Please refer this to get an idea about Duck Typing

    http://haacked.com/archive/2007/08/19/why-duck-typing-matters-to-c-developers.aspx/

提交回复
热议问题