What is polymorphism, what is it for, and how is it used?

前端 未结 28 2806
南笙
南笙 2020-11-21 07:08

What is polymorphism, what is it for, and how is it used?

28条回答
  •  梦毁少年i
    2020-11-21 07:39

    Generally speaking, it's the ability to interface a number of different types of object using the same or a superficially similar API. There are various forms:

    • Function overloading: defining multiple functions with the same name and different parameter types, such as sqrt(float), sqrt(double) and sqrt(complex). In most languages that allow this, the compiler will automatically select the correct one for the type of argument being passed into it, thus this is compile-time polymorphism.

    • Virtual methods in OOP: a method of a class can have various implementations tailored to the specifics of its subclasses; each of these is said to override the implementation given in the base class. Given an object that may be of the base class or any of its subclasses, the correct implementation is selected on the fly, thus this is run-time polymorphism.

    • Templates: a feature of some OO languages whereby a function, class, etc. can be parameterised by a type. For example, you can define a generic "list" template class, and then instantiate it as "list of integers", "list of strings", maybe even "list of lists of strings" or the like. Generally, you write the code once for a data structure of arbitrary element type, and the compiler generates versions of it for the various element types.

提交回复
热议问题