What's the difference between Polymorphism and Multiple Dispatch?

后端 未结 7 1351
难免孤独
难免孤独 2021-01-30 10:52

...or are they the same thing? I notice that each has its own Wikipedia entry: Polymorphism, Multiple Dispatch, but I\'m having trouble seeing how the concepts differ.

<

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-30 11:37

    With multiple dispatch, a method can have multiple arguments passed to it and which implementation is used depends on each argument's type. The order that the types are evaluated depends on the language. In LISP, it checks each type from first to last. Languages with multiple dispatch make use of generic functions, which are just function declarations and aren't like generic methods, which use type parameters.

    Multiple dispatch allows for subtyping polymorphism of arguments for method calls.

    Single dispatch also allows for a more limited kind of polymorphism (using the same method name for objects that implement the same interface or inherit the same base class). It's the classic example of polymorphism, where you have methods that are overridden in subclasses.

    Beyond that, generics provide parametric type polymorphism (i.e., the same generic interface to use with different types, even if they're not related — like List: it can be a list of any type and is used the same way regardless).

提交回复
热议问题