Computer Science

Polymorphism programming

Polymorphism programming is a concept in object-oriented programming that allows objects of different classes to be treated as if they were the same type of object. This is achieved through inheritance and method overriding, which allows for more flexible and reusable code. Polymorphism is a key feature of many programming languages, including Java and C++.

Written by Perlego with AI-assistance

10 Key excerpts on "Polymorphism programming"

  • Book cover image for: First Course in Type Theory, A
    ________________________ WORLD TECHNOLOGIES ________________________ Chapter 3 Type Polymorphism and Type System Type polymorphism In computer science, polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface. The concept of parametric polymorphism applies to both data types and functions. A function that can evaluate to or be applied to values of different types is known as a polymorphic function. A data type that can appear to be of a generalized type (e.g., a list with elements of arbitrary type) is designated polymorphic data type like the generalized type from which such specializations are made. There are two fundamentally different kinds of polymorphism, originally informally described by Christopher Strachey in 1967. If the function denotes different and potentially heterogeneous implementations depending on a limited range of individually specified types and combinations, it is called ad-hoc polymorphism . Ad-hoc poly-morphism is supported in many languages using function and method overloading. If all code is written without mention of any specific type and thus can be used transparently with any number of new types, it is called parametric polymorphism . John C. Reynolds (and later Jean-Yves Girard) formally developed this notion of polymorphism as an extension to the lambda calculus (called the polymorphic lambda calculus, or System F). Parametric polymorphism is widely supported in statically typed functional programming languages. In the object-oriented programming community, programming using parametric polymorphism is often called generic programming . In object-oriented programming, inclusion polymorphism is a concept in type theory wherein a name may denote instances of many different classes as long as they are related by some common super class.
  • Book cover image for: Logic Programming & Type Theory
    ________________________ WORLD TECHNOLOGIES ________________________ Chapter 9 Type Polymorphism and Type System Type polymorphism In computer science, polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface. The concept of parametric polymorphism applies to both data types and functions. A function that can evaluate to or be applied to values of different types is known as a polymorphic function. A data type that can appear to be of a generalized type (e.g., a list with elements of arbitrary type) is designated polymorphic data type like the generalized type from which such specializations are made. There are two fundamentally different kinds of polymorphism, originally informally described by Christopher Strachey in 1967. If the function denotes different and potentially heterogeneous implementations depending on a limited range of individually specified types and combinations, it is called ad-hoc polymorphism . Ad-hoc poly-morphism is supported in many languages using function and method overloading. If all code is written without mention of any specific type and thus can be used transparently with any number of new types, it is called parametric polymorphism . John C. Reynolds (and later Jean-Yves Girard) formally developed this notion of polymorphism as an extension to the lambda calculus (called the polymorphic lambda calculus, or System F). Parametric polymorphism is widely supported in statically typed functional programming languages. In the object-oriented programming community, programming using parametric polymorphism is often called generic programming . In object-oriented programming, inclusion polymorphism is a concept in type theory wherein a name may denote instances of many different classes as long as they are related by some common super class.
  • Book cover image for: IT Interview Guide for Freshers
    eBook - ePub

    IT Interview Guide for Freshers

    Crack your IT interview with confidence

    Polymorphism is the feature of OOPs wherein an object can take multiple forms based on its type or class. The best example of polymorphism is invoking derived class functions through a base class reference at runtime. There are two types of polymorphism:
    • Static polymorphism also known as compile time polymorphism: Polymorphism that is resolved during the compiler time is known as static polymorphism. Method overloading is an example of compile time polymorphism. Method Overloading allows you to have more than one method having the same name, if the parameters of methods are different in number, sequence and data types of parameters.
    • Dynamic polymorphism also known as runtime polymorphism: Dynamic or runtime polymorphism is also known as method overriding in which a call to an overridden function is resolved during runtime, not at the compile time. It means having two or more methods with the same name, same signature but with different implementation.
    Figure 6.12: Different types of polymorphism

    Describe method overloading.

    Overloading is a OO concept that facilities declaring and defining several methods with the same name, but with different method signatures. Methods are identified based on:
    • Number of parameters
    • Types of parameters
    • Order of parameters
    Example: int addition(int a,int b) { return a+b;} int addition (int a,int b,int c) { return a+b+c;} float addition (float a, float b, float c) { return a+b+c;}

    In case the original method is non-static can we declare an overridden method to be static?

    The two virtual methods in the base and derived class must have the same method signatures.

    What is the significance of the virtual keyword ?

    A virtual keyword is leveraged while defining a class to mandate that the methods of the base class need to be overridden in the derived classes.

    What is a virtual function?

    A virtual function is a member function of a class, and its functionality can be overridden in its derived class. This function can be implemented using a keyword called virtual, and it can be given during function declaration. A virtual function can A token in C++, and it can be achieved in C Language using function pointers or pointers to function.
  • Book cover image for: Object-Oriented Programming with ABAP Objects
    • James Wood, Joseph Rupert(Authors)
    • 2015(Publication Date)
    • SAP PRESS
      (Publisher)
    The term polymorphism literally means “many forms”. From an object-oriented perspective, polymorphism works in concert with inheritance to make it possible for various types within an inheritance tree to be used interchangeably. In this chapter, we’ll learn how to harness this power to create highly flexible program designs using ABAP Objects. 6 Polymorphism In the previous chapter, we learned how to define inheritance relationships between related classes. From there you will recall that the basic litmus test we used to identify these relationships was to ask ourselves whether or not a given class was a more specific type of a particular superclass. For example, a Dog is a specific type of Mammal. So, instead of creating a standalone Dog class, it makes sense to define the Dog class as a subclass of Mammal so that it can inherit selected features from Mammal. When we look at inheritance in this light, it’s easy to see its obvious benefits in terms of code reuse. However, as it turns out, there’s another (and arguably more important) dimension of the “is-a” relationship that we haven’t yet considered. Since the classes in an inheritance tree share a common public interface, it’s technically possible for a given subclass to respond to any request (i.e., method call) directed at its superclass. This aspect of the inheritance relationship is referred to as interface inheritance. When we combine interface inheritance with the ability for subclasses to redefine/override the implementation of their inherited methods, we end up in a situation where clients no longer have to worry about the types of objects they’re interfacing with: they simply issue requests (method calls) and let the objects themselves figure out how to process the requests in type-specific ways
  • Book cover image for: Mastering JavaScript Object-Oriented Programming
    Support of polymorphism brings benefits in programming that go toward the overall goal of OOP. Mainly, it reduces coupling in our application, and in some cases, allows to create more compact code. The most common ways to support polymorphism with a programming language include:
    • Methods that take parameters with different data types (overloading)
    • Management of generic types, not known in advance (parametric polymorphism)
    • Expressions whose type can be represented by a class and classes derived from it (subtype polymorphism or inclusion polymorphism )
    In most languages, overloading is what happens when you have two methods with the same name but different signatures. At compile time, the compiler works out which method to call based on matching between types of invocation arguments and method's parameters. The following is an example of method overloading in C#:
    public int CountItems(int x) { return x.ToString().Length; } public int CountItems(string x) { return x.Length; }
    The CountItems() method has two signatures-one for integers and one for strings. This allows to count the number of digits in a number or the number of characters in a string in a uniform manner, just calling the same method.
    Overloading can also be expressed through methods with different numbers of arguments, as shown in the following C# example: public int Sum(int x, int y) { return Sum(x, y, 0); } public int Sum(int x, int y, int z) { return x+ y + z; }
    Here, we have the Sum() method that is able to sum two or three integers. The correct method definition will be detected on the basis of the number of arguments passed.
    As JavaScript developers, we are able to replicate this behavior in our scripts. For example, the C# CountItems()
  • Book cover image for: Programming language theory
    • Alvin Albuero De Luna(Author)
    • 2023(Publication Date)
    • Arcler Press
      (Publisher)
    Figure 8.2 depicts this circumstance. Any dynamically-typed object-oriented languages will naturally have polymorphism. In certain ways, polymorphism transforms strongly typed languages into one that is somewhat constantly typed. This happens when method calls are bound to exact techniques. A polymorphism variable’s category is dynamic (America, 1989; Bruce, 2003). Figure 8.2. Dynamically bound. Source: https://www.researchgate.net/figure/Dynamically-and-statically- bound-links_fig2_2815700. 8.3. DESIGN ISSUES FOR OBJECT-ORIENTED LANGUAGES When creating the computer language characteristics that permit inherited and dynamically binding, a variety of concerns must be taken into account. This section goes through the ones we believe are most significant (Papathomas, 1989; Rumbaugh et al., 1991). 8.3.1. The Exclusivity of Objects An object framework that incorporates all additional type notions is created by a language developer who is wholly dedicated to the object-oriented Programming Language Theory 210 paradigm of computing. In just this mentality, everything that a simple scalar number to an entire software application is an object. The beauty and strict homogeneity of a language as well as its application are advantages of this decision. The main drawback is that since simple operations had to go through a message-passing mechanism, they often are slower than equivalent actions in such a declarative paradigm, in which such simple processes are implemented by single machine code. All categories are subclasses in this most basic paradigm of object-oriented computing. Between defined and consumer classes, there is no differentiation. In actuality, all types are handled equally, and message forwarding is used for every computation (Korson and McGregor, 1990; Chiba, 1998).
  • Book cover image for: Modern Compiler Implementation in Java
    16 Polymorphic Types poly-mor-phic: able to assume different forms Webster’s Dictionary Some functions execute in a way that’s independent of the data type on which they operate. Some data structures are structured in the same way regardless of the types of their elements. As an example, consider a function to concatenate linked lists in Java. We define a List class, subclasses for empty and nonempty lists, and a (nonde- structive) append method: abstract class IntList { IntList append(IntList more); } class IntCons extends IntList { Integer head; IntList tail; IntCons (Integer head, IntList tail) { this.head=head; this.tail=tail; } IntList append(IntList more) { return new IntCons(head, tail.append(more)); } } class IntNull extends IntList { IntNull () {} IntList append(IntList more) { return more; } } There’s nothing about the code for the IntList data type or the append method that would be any different if the element type were String or Tree instead of Integer. We might like append to be able to work on any kind of 335 CHAPTER SIXTEEN. POLYMORPHIC TYPES list. We could, of course, use the word Object instead of Integer to declare head, but then if we unintentionally mixed Integers and Strings as elements of the same List, the compiler’s type-checker wouldn’t be able to give us useful feedback: we’d get a runtime exception at a downcast somewhere. A function is polymorphic (from the Greek many+shape) if it can operate on arguments of different types. There are two main kinds of polymorphism Parametric polymorphism. A function is parametrically polymorphic if it fol- lows the same algorithm regardless of the type of its argument. The Ada or Modula-3 generic mechanism, C++ templates, or ML type schemes are exam- ples of parametric polymorphism. Overloading. A function identifier is overloaded if it stands for different algo- rithms depending on the type of its argument.
  • Book cover image for: The Mathematica® Programmer
    • Roman E. Maeder(Author)
    • 2014(Publication Date)
    • Academic Press
      (Publisher)
    Polymorphic functions are functions that can handle several different types of arguments. We look at ways of implementing such functions. First we present three LlSP-like implementations using dispatch tables, data-driven programming, and message passing. Then we look at various ways of implementing objects, that is, data elements that have built in all the functions that can be applied to them. This concept provides for a high degree of modularity and lays the groundwork for a discussion of object-oriented programming in Chapter 4. About the illustration overleaf: The location of primes. The integers are represented in a spiral fashion (with the number one in the center) and primes are marked black. The visible diagonal lines represent certain arithmetic progressions containing many primes. The picture was produced with PrimesPlot[99], using the package Spirals.m. See also Pictures.m. A similar plot showing the number of divisors of integers is given in Plate 1. 36 3.1 Polymorphic Operations 37 3.1 Polymorphic Operations One tool for writing reusable software is polymorphism. Often, the same function needs to be applied to data of different types. Rather than write separate functions for each data type, we try to write one function that can handle data of different types. We will look at several ways to implement this idea. We will explain our ideas with an example: polymorphic arithmetic with complex numbers. We will represent complex numbers in two different ways: Cartesian (rectangular) coordinates and polar coordinates. The arithmetic functions must therefore allow for arguments of either of these types. Note that we do not work with Mathematical built-in complex numbers in this example. Instead, we will implement complex numbers as abstract data types.
  • Book cover image for: Data Structures and Algorithms in C++
    • Michael T. Goodrich, Roberto Tamassia, David M. Mount(Authors)
    • 2011(Publication Date)
    • Wiley
      (Publisher)
    For each pattern, be it for algorithm engineering or software engineering, we explain its general use and we illustrate it with at least one concrete example. 2.2. Inheritance and Polymorphism 71 2.2 Inheritance and Polymorphism To take advantage of hierarchical relationships, which are common in software projects, the object-oriented design approach provides ways of reusing code. 2.2.1 Inheritance in C++ The object-oriented paradigm provides a modular and hierarchical organizing struc- ture for reusing code through a technique called inheritance. This technique allows the design of generic classes that can be specialized to more particular classes, with the specialized classes reusing the code from the generic class. For example, sup- pose that we are designing a set of classes to represent people at a university. We might have a generic class Person, which defines elements common to all people. We could then define specialized classes such as Student, Administrator, and In- structor, each of which provides specific information about a particular type of person. A generic class is also known as a base class, parent class, or superclass. It defines “generic” members that apply in a multitude of situations. Any class that specializes or extends a base class need not give new implementations for the general functions, for it inherits them. It should only define those functions that are specialized for this particular class. Such a class is called a derived class, child class, or subclass. Let us consider an example to illustrate these concepts. Suppose that we are writing a program to deal with people at a university. Below we show a partial implementation of a generic class for a person. We use “// ...” to indicate code that is irrelevant to the example and so has been omitted. class Person { // Person (base class) private: string name; // name string idNum; // university ID number public: // .
  • Book cover image for: Object-Orientation, Abstraction, and Data Structures Using Scala
    3 The formal way to describe the memory overhead here is O (1). Chapter 7 includes a more complete description of this notation and the general topic of asymptotic orders. 118 Object-Orientation, Abstraction, and Data Structures Using Scala FIGURE 4.1 : This figure shows a limited set of options for the subtyping relationships of animals as a UML diagram. to errors and hard to work with. Plus, one would expect that with so few changes between the versions, it should be possible to make one version that handles them all. To put it a different way, we should be able to abstract out the differences so that we have one version that will work in different situations. In this case, part of that abstraction is abstracting over types. To do that we need polymorphism. There are multiple different styles of polymorphism, but we can group them into two broad categories: universal and ad-hoc. Universal polymorphism implies that code can work with an infinite number of types. By contrast, ad-hoc polymorphism only works with a finite number of types. We will primarily consider universal polymorphism in two different forms, inclusion polymorphism and parametric polymorphism . 4.2 Inclusion Polymorphism (Inheritance and Subtyping) Inclusion polymorphism is a form of universal polymorphism that we get from subtyp-ing . That is to say, when all elements of one type are also part of another, more general, type. This type of relationship is produced by a programming language feature called in-heritance. We often say that inheritance models an “is-a” relationship. There are lots of examples of this in the real world. A car is a vehicle, as is a bus. A cat is a mammal, as are dogs and humans. This second example shows another feature of the is-a relationship—it can have multiple levels. We could consider the broad category of animals. There are several subtypes of animals including birds, reptiles, amphibians, and mammals.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.