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"

  • 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
  • AP Computer Science A Premium, 2024: 6 Practice Tests + Comprehensive Review + Online Practice
    UnderGrad .
    Polymorphism is the mechanism of selecting the appropriate method for a particular object in a class hierarchy. The correct method is chosen because, in Java, method calls are always determined by the type of the actual object, not the type of the object reference. For example, even though s, g , and u are all declared as type Student, s.computeGrade(), g.computeGrade() , and u.computeGrade() will all perform the correct operations for their particular instances. In Java, the selection of the correct method occurs during the run of the program.
    Here is a simple example. Now consider this hierarchy of classes, and the declarations that follow it:
    Suppose the Dog class has this method:
    public void eat() { /* implementation not shown */ }
    And each of the subclasses, Poodle, PitBull, Dachshund , etc., has a different, overridden eat method. Now suppose that allDogs is an ArrayList<Dog> where each Dog declared above has been added to the list. Each Dog in the list will be processed to eat by the following lines of code:
    Polymorphism is the process of selecting the correct eat method, during run time, for each of the different dogs.
    Recall that constructors are not inherited, and if you use the keyword super in writing a constructor for your subclass, the line containing it should precede any other code in the constructor.
    Recall also that if the superclass does not have a no-argument constructor, then you must write an explicit constructor for the subclass. If you don’t do this, later code that tries to create a subclass object will get a compile-time error. This is because the compiler will generate a default constructor for the subclass that tries to invoke the no-argument constructor of the superclass.

    Dynamic Binding (Late Binding)

    Making a run-time decision about which instance method to call is known as dynamic binding or late binding. Contrast this with selecting the correct method when methods are overloaded (see p. 106 ) rather than overridden. The compiler selects the correct overloaded method at compile time by comparing the methods’ signatures. This is known as static binding, or early binding. In polymorphism, the actual method that will be called is not determined by the compiler. Think of it this way: The compiler determines if a method can be called (i.e., does the method exist in the class of the reference?), while the run-time environment determines how
  • 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()
  • 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.
  • Programming in C#: Exam 70-483 (MCSD) Guide
    eBook - ePub

    Programming in C#: Exam 70-483 (MCSD) Guide

    Learn basic to advanced concepts of C#, including C# 8, to pass Microsoft MCSD 70-483 exam

    • Simaranjit Singh Bhalla, SrinivasMadhav Gorthi(Authors)
    • 2019(Publication Date)
    • Packt Publishing
      (Publisher)
    Now, let's see how runtime polymorphism works. In the following code, we are declaring an object of the base Animal class and pointing it to an object of the derived class:
    Animal animal = new Animal();animal.numOfHands = 2;animal.numOfLegs = 4;animal.Speak();animal = new Dog("Labrador", 0, 4);animal.Speak();animal = new Human("India", 2, 2);animal.Speak();Console.ReadLine();
    Once we execute this code, we will notice that, based on the class object reference that the base object animal is pointing to, the appropriate implementation of the Speak method will be loaded. This loading is decided at runtime, which is why this is called runtime polymorphism :
    Passage contains an image

    Summary

    In this chapter, we learned about object-oriented programming, which is the main essence of any high-level programming language, including C#. We learned about the four pillars of OOP, that is, encapsulation, abstraction, polymorphism, and inheritance, and understood how they help us write applications that are easy to maintain, are scalable, and have a good amount of reuse.
    We learned how encapsulation helps us in keeping our code structured by grouping together all the related properties and methods in one class. Then, we learned how abstraction helps us reduce the complexity of a module that is exposed to the entire application. Using abstraction, we can make sure that all the complexities of a class are not exposed to outside classes, which also helps us maintain the application better. We also learned how we can use both runtime and static polymorphism to implement similar functionalities that can be reused across different inputs, thus helping us reuse our code throughout the application. Finally, we learned how inheritance helps us have more control over the application's implementation. Using inheritance, we can make sure that similar classes implement a set of properties and methods that are common across them.
    While writing any program in C#, it's highly important that we keep these principles in mind. The biggest mistake that some C# programmers make these days is they don't utilize these core principles of OOP programming and, instead, the program that's written resembles more of a procedural language program. From a maintenance perspective, it helps us a lot as, to some extent, it ensures that the bug fixes in one module do not impact the complete application.
  • Learn Java 17 Programming
    Encapsulation is often defined either as data hiding or a bundle of publicly accessible methods and privately accessible data. In a broad sense, encapsulation is controlled access to an object’s properties.
    The snapshot of values of object properties is called an object state . This is data that is encapsulated. So, encapsulation addresses the main issue that motivated the creation of object-oriented programming – better management of concurrent access to shared data, such as the following:
    class A {   private String prop = "init value";   public void setProp(String value){      prop = value;   }   public String getProp(){      return prop;   } }
    As you can see, to read or modify the value of the prop property, we cannot access it directly because of the private access modifier. Instead, we can do it only via the setProp(String value) and getProp() methods.

    Polymorphism

    Polymorphism is the ability of an object to behave as an object of a different class or as an implementation of a different interface. It owes its existence to all the concepts that have been mentioned previously – inheritance, interface, and encapsulation. Without them, polymorphism would not be possible.
    Inheritance allows an object to acquire or override the behaviors of all its ancestors. An interface hides from the client code the name of the class that implemented it. The encapsulation prevents exposing the object state.
    In the following sections, we will demonstrate all these concepts in action and look at the specific usage of polymorphism in the Polymorphism in action section.

    Class

    A Java program is a sequence of statements that express an executable action. The statements are organized in methods, and methods are organized in classes. One or more classes are stored in .java files. They can be compiled (transformed from the Java language into a bytecode) by the javac Java compiler and stored in .class files. Each .class file contains one compiled class only and can be executed by JVM.
    A java command starts JVM and tells it which class is the main one, the class that has the method called main() . The main method has a particular declaration – it has to be public static , must return void , has the name main , and accepts a single parameter of an array of a String
  • Data-Oriented Programming
    eBook - ePub

    Data-Oriented Programming

    Reduce software complexity

    • Yehonathan Sharvit(Author)
    • 2022(Publication Date)
    • Manning
      (Publisher)
    DAVE   I see. So an anthropomorphic book is a book where animals have human traits. The word sounds related to polymorphism.
      THEO   Absolutely. Polymorphism comes from the Greek polús, which means many, and morphe–, which, again, means form.
      DAVE   That makes sense. Polymorphism is the ability of different objects to implement the same method in different ways. That brings me back to my animal example. In OOP, I’d define an IAnimal interface with a greet method, and each animal class would implement greet in its own way. Here, I happen to have an example.
    Listing 13.1 OOP polymorphism illustrated with animals
    interface IAnimal { public void greet(); } class Dog implements IAnimal { private String name; public void greet() { System.out.println("Woof woof! My name is " + animal.name); } } class Cat implements IAnimal { private String name; public void greet() { System.out.println("Meow! I am " + animal.name); } } class Cow implements IAnimal { private String name; public void greet() { System.out.println("Moo! Call me " + animal.name); } }
      THEO   Let me challenge you a bit. What is the fundamental difference between OOP polymorphism and a switch statement?
      DAVE   What do you mean?
      THEO   I could, for instance, represent an animal with a map having two fields, name and type , and call a different piece of code, depending on the value of type .
    Theo pulls his laptop from its bag and fires it up. While the laptop is booting up, he enjoys another taste of that wonderful orange juice. When the laptop is ready, he quickly types in the example switch case. Meanwhile, Dave has finished his glass of orange juice.
  • C++ Fundamentals
    eBook - ePub

    C++ Fundamentals

    Hit the ground running with C++, the language that supports tech giants globally

    • Antonio Mallia, Francesco Zoffoli(Authors)
    • 2019(Publication Date)
    • Packt Publishing
      (Publisher)
    In the previous section, we mentioned that inheritance is a solution that allows you to change the behavior of code while a program is running. This is because inheritance enables polymorphism in C++.
    Polymorphism means many forms and represents the ability of objects to behave in different ways.
    We mentioned earlier that templates are a way to write code that works with many different types at compilation time and, depending on the types used to instantiate the template, the behavior will change.
    This kind of pattern is called static polymorphism – static because it is known during compilation time. C++ also supports dynamic polymorphism – having the behavior of methods change while the program is running. This is powerful because we can react to information we obtain only after we have compiled our program, such as user input, values in configurations, or the kind of hardware the code is running on. This is possible thanks to two features – dynamic binding and dynamic dispatch .

    Dynamic Binding

    Dynamic binding is the ability for a reference or a pointer of a base type to point to an object of a derived type at runtime. Let's explore the following example:
    struct A { }; struct B: A{ }; struct C: A { }; //We can write B b; C c; A& ref1 = b; A& ref2 = c; A* ptr = nullptr; if (runtime_condition()) { ptr = &b; } else { ptr = &c; }
    Note
    To allow dynamic binding, the code must know that the derived class derives from the base class.
    If the inheritance's visibility is private , then only code inside the derived class will be able to bind the object to a pointer or reference of the base class.
    If the inheritance is protected , then the derived class and every class deriving from it will be able to perform dynamic binding. Finally, if the inheritance is public , the dynamic binding will always be allowed .
    This creates the distinction between the static type and the dynamic (or run-time) type. The static type is the type we can see in the source code. In this case, we can see that ref1 has a static type of a reference to the A
  • Learn Java 12 Programming
    eBook - ePub

    Learn Java 12 Programming

    A step-by-step guide to learning essential concepts in Java SE 10, 11, and 12

    implement an interface. Since an interface describes how you can interact with an object, but not how an object responds to the interaction, different objects can behave differently while implementing the same interface.
    In Java, a class can have only one direct parent but can implement many interfaces. The ability to behave as any of its ancestors and adhere to multiple interfaces is called polymorphism .
    In this chapter, we will look at these OOP concepts and how they are implemented in Java. The topics discussed include the following:
    • OOP concepts
    • Class
    • Interface
    • Overloading, overriding, and hiding
    • Final variable, method, and class
    • Polymorphism in action
    Passage contains an image

    OOP concepts

    As we have already stated in the introduction, the main OOP concepts are as follows:
    • Object/Class : It defines a state (data) and behavior (methods) and holds them together
    • Inheritance : It propagates behavior down the chain of classes connected via parent-child relationships
    • Abstraction/Interface : It describes how the object data and behavior can be accessed. It isolates (abstracts) an object's appearance from its implementations (behavior)
    • Encapsulation : It hides the state and details of the implementation
    • Polymorphism : It allows an object to assume an appearance of implemented interfaces and behave as any of the ancestor classes
    Passage contains an image

    Object/class

    In principle, you can create a very powerful application with minimal usage of classes and objects. It became even easier to do this after functional programming was added to Java 8, to JDK, which allowed you to pass around behavior as a function. Yet passing data (state) still requires classes/objects. This means that the position of Java as an OOP language remains intact.
    A class defines the types of all internal object properties that hold the object state. A class also defines object behavior expressed by the code of the methods. It is possible to have a class/object without a state or without a behavior. Java also has a provision for making the behavior accessible statically—without creating an object. But these possibilities are no more than just additions to the object/class concept that was introduced for keeping the state and behavior together.
  • Computer Systems Architecture
    This contributes to the modular design, since it is relatively simple to replace an existing object by a different one, provided the interface remains unchanged. •  Composition, which refers to the fact that objects can be constructed by integrating other objects while providing a combined functionality. Nevertheless, the internal structure is unknown to the client objects. As with encapsulation, composition increases the modularity and flexibility of changes. •  Inheritance, which refers to the object’s ability to inherit from a parent object and use the functionality that was already defined by the base or parent object. From a software-engineering perspective, this represents an important feature that allows rapid development of derived classes and objects. This ability has its merit in lowering the costs associated with maintaining the system and introducing changes. •  Polymorphism, which, while it is based on inheritance, provides the means not only to inherit the behavior from the parent object but also to modify it. By overriding some of the inherited behavior, an object can benefit from the two worlds. On the one hand, it can inherit the required functionality, and, on the other hand, it can replace the undesired behavior with a different one. The object-oriented development paradigm reflects on all previous architectures, since each one of the previously described architectures can be implemented using an OOA. Figure 11.9 depicts and object-oriented system and the communications between the subsystems defined. Subsystems, or packages of components, are depicted as folders (a rectangle with a small rectangle on its top left side). The left side of the figure defines a general overview of a client/server architecture. The client sends messages to the server (in the direction of the arrow), but the server does not initiate communication with the client. On the right side, there are two peers that communicate by sending messages in both directions
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.