What is polymorphism?

Started by chinmay.sahoo, 01-05-2017, 03:27:29

Previous topic - Next topic

chinmay.sahooTopic starter

Poly stands for "many" and morph stands for "form".   It simply means the ability of an object to take more then one form.


SeoDezin

#1
Polymorphism, in the context of object-oriented programming, is a concept that allows objects of different classes to be treated as objects of a common superclass. Different types of polymorphism can exist, including:

1. **Subtype polymorphism**: This type of polymorphism, also referred to as inclusion polymorphism, is made possible by inheritance. This means that a class can inherit methods from a superclass, and various subclasses can then be defined that implement or extend these inherited methods in different ways.

2. **Parametric polymorphism**: This concept allows code to be written in a generic way, making it applicable to objects/values of many different types. Many statically typed languages, like Java or C#, support polymorphism through the use of generics.

3. **Ad hoc polymorphism** (also known as function or operator polymorphism): This type of polymorphism is achieved when functions can be applied to arguments of different types but it behaves differently based on the type of the argument passed. Function overloading is a common example of ad hoc polymorphism, where different implementations of a function can be invoked based on the type or number or arguments.

4. **Coercion polymorphism**: This happens when a type can automatically convert to another type as required by the operation in context. For example, you might use an integer where a float is expected and the programming language automatically converts the integer into a float.

The primary benefit of polymorphism in programming is that it promotes code reusability and efficiency, making programs more modular and easier to maintain and debug. It is one of the core concepts of object-oriented programming, along with inheritance and encapsulation.


I can expand more on polymorphism.

Polymorphism is essentially a way to use a class in multiple forms. One of the fundamental characteristics of polymorphism is that it lets you create one general class with characteristics that are common across a set of subclasses.

For example, consider a general class called "Animal". The "Animal" class might have characteristics like "color", "size", or "weight", and behaviors like "eat" or "move". Now, you can have different types of animals, like "Dog", "Cat", or "Bird", which are classes that extend or inherit from the "Animal" class. Each of these subclasses could have additional characteristics and behaviors that are unique to them.

Despite their unique characteristics, because a "Dog", "Cat", or "Bird" is still an "Animal", you can interact with each through the same interface defined in the "Animal" class. This is one example of polymorphism. You can interact with several different subclasses in the same way, even though under the hood they might behave differently.

For example, the "Dog" class might override the "move" method to make a dog walk or run, while the "Bird" class might override the "move" method to make a bird fly. But despite these differences, both a "Dog" object and a "Bird" object could be passed to a function that expects an "Animal" object and invokes the "move" method.

public void makeItMove(Animal animal) {
    animal.move();
}
In this example, makeItMove doesn't need to know the detailed type of animal; it treats all inputs as type Animal. This method exhibits polymorphic behavior because it can handle objects of varying types.

Beyond these basics, there are more complex uses of polymorphism. For example, in some languages like C++, you have something called "virtual functions", which are member functions that you expect to be redefined in derived classes. Java, on the other hand, has "interfaces" that specify a contract that certain classes have to follow, allowing polymorphic behavior between classes that implement the same interface even if they have no common superclass besides Object.

Through these various mechanisms, polymorphism makes your programs more modular and extensible—since you can introduce new subclasses without needing to change the functions that interact with the superclass—and it allows parts of your program to be abstracted away behind interfaces, which can decrease coupling between different sections of a large codebase.

let's delve further into the topic of polymorphism. To clarify how it works, let's discuss an actual code example in Java:

// Here is an interface:
public interface Shape {
    public void draw();
}

// Multiple different classes implement the Shape interface:
public class Circle implements Shape {
    public void draw() {
        System.out.println("Drawing a circle.");
    }
}

public class Rectangle implements Shape {
    public void draw() {
        System.out.println("Drawing a rectangle.");
    }
}

// Usage:
public class Main {
    public static void main(String[] args) {
        Shape[] shapes = new Shape[2];
        shapes[0] = new Circle();
        shapes[1] = new Rectangle();

        for (Shape shape : shapes) {
            shape.draw();  // Polymorphic behavior!
        }
    }
}
In this example, Shape is an interface that declares a method draw(). There are two classes Circle and Rectangle implementing the Shape interface and providing their own implementations of draw(). In the main() method of the Main class, an array of type Shape (the interface type) is created and instances of Circle and Rectangle are stored in it.

The magic of the polymorphic behavior is shown in the loop that follows. Even though the type of the reference variable is Shape (a super type), the JVM (Java Virtual Machine) knows the actual type of the object (whether it is a Circle or Rectangle) and calls the appropriate draw() method. This is known as dynamic method dispatch or runtime polymorphism.

This example illustrates how polymorphism offers a way to design for change. You can add a new shape class (like Triangle), and as long as it adheres to the Shape interface, the drawing code could accommodate it without any modification.

It's worth mentioning that in Java, polymorphism is facilitated through its feature of allowing reference variable types to be superclasses or interfaces of the actual object type. In the above example, Shape was an interface reference that was able to refer to Circle and Rectangle objects.

In other languages such as C++, similar behavior can be achieved through function pointers or virtual functions, which ensure that the proper function is invoked based on the actual type of the object involved in the call, not the declared type of the pointer used to make the call.

we've discussed polymorphism's fundamental concept and seen how it's used in a practical example, showcasing how it enables a single reference type to express behavior for multiple actual types. This characteristic improves code maintainability and extensibility.

Now, let's delve a bit deeper into the types of polymorphism we usually encounter in programming:

Subtyping (Inclusion Polymorphism): This is the type of polymorphism we've discussed so far, where a name can denote instances of many different classes as long as they're related by some common superclass. This allows us to write code that can operate on objects of the superclass but works with any subclass. Subtyping polymorphism is often seen in object-oriented languages like Java, C++, and many others.

Parametric Polymorphism: This type is when one or more types are not specified by name but by abstract symbols that can represent any type. This is the kind of polymorphism that's seen in generics in languages like Java or C++ and templates in C++. Languages like Haskell and Scala also support parametric polymorphism.

Here's an example in Java using generics:

public class Box<T> {
    private T t;

    public void set(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }
}
Box class can be created for different data types. T is a type parameter that will be replaced by a real type when an object of type Box is created.

Ad-hoc Polymorphism: This is when a function symbol is associated with many implementations depending on a combination of arguments, which is determined at runtime. Overloaded functions or methods in languages like Java, C++, or Python are examples of this kind of polymorphism.

An example of ad-hoc polymorphism in Java through method overloading:

public class Greeter {
    public void greet() {
        System.out.println("Hello, world!");
    }

    public void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }
}
As we can see, polymorphism is not just a concept tied to object-oriented programming. It's a very general and powerful idea that, when used appropriately, can help create easier-to-read, more adaptable code. It facilitates the creation of abstract classes or interfaces, which can be developed against, reducing coupling in code. It also simplifies APIs and helps us deal with complexity by allowing us to focus on the essential aspects of a component's behavior without needing to know its exact type.

Let's delve further into polymorphism from a different angle, looking at how polymorphism relates to the SOLID principles in software design, and observing how it assists in structuring code for change, maintainability, and reusability in real-world software projects.

1. **SOLID Principles and Polymorphism**: SOLID is an acronym representing five principles of reusable and maintainable object-oriented software design, namely:

   - Single Responsibility Principle (SRP)
   - Open-Closed Principle (OCP)
   - Liskov Substitution Principle (LSP)
   - Interface Segregation Principle (ISP)
   - Dependency Inversion Principle (DIP)

   The Liskov Substitution Principle (LSP) is directly related to polymorphism. The principle formally states that "if S is a subtype of T, then objects of type T may be replaced with objects of type S, without breaking the program." This principle essentially ensures that a child class can do everything its parent can.

2. **Real-World Software Projects**: In real-world codebases, polymorphism is a tool applied in many software design patterns to make the code more flexible and modular. Here are a few examples:

   - **Strategy Pattern**: It's a behavioral design pattern that determines a family of algorithms, encapsulates each one into separate classes, making them interchangeable at runtime. The Context class maintains a reference to a Strategy object and delegates it executing the behavior. This implementation let's us vary the strategy used independently from clients that use it, showcasing polymorphism.

   - **Factory Pattern**: It's a creational pattern that uses factory methods to handle the creation of objects without specifying the exact class of object that will be created. This is done through creating objects by calling a factory method—either specified in an interface and implemented by child classes or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.

   - **Adapter Pattern**: It's a structural design pattern that allows objects with incompatible interfaces to work together. An Adapter wraps an existing class with a new interface so that it becomes compatible with the client's interface, thereby achieving polymorphism.

The ability to use polymorphism in these ways gives us a lot of power when designing our software architecture. Essentially, it is a way to achieve flexible inter-operation of related types without unnecessarily tying code to specific data types. Polymorphism can help to hide complexity, isolate impacts of changes, and allow advanced software design techniques to result in clean, understandable, and maintainable code.


Lauraponting

Polymorphism in Java:
Polymorphism in java is a mechanism  which we can perform a single action by different ways.
"poly" means many and "morphs" means forms.
There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism.
We can perform polymorphism in java by method overloading and method overriding.
If you overload static method in java, it is the example of compile time polymorphism.
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time.
  •  

richardmsmith

polymorphism in Java:
The word "poly" means many and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.

EugeneHill

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
For instance, suppose there is a class called Animal, and a class called Dog that inherits from Animal.

Polymorphism is the ability to treat any Dog object as an Animal object like so:
Dog* dog = new Dog;
Animal* animal = dog;


greatshivam

The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form.
Real life example of polymorphism, a person at the same time can have different characteristic. Like a man at the same time is a father, a husband, an employee. So the same person posses different behavior in different situations. This is called polymorphism.
Polymorphism is considered as one of the important features of Object Oriented Programming.

In C++ polymorphism is mainly divided into two types:

1:Compile time Polymorphism
2:Runtime Polymorphism
  •  

Lishmalinyjames

Polymorphism is one of the core concepts in OOP languages. It describes the concept that different classes can be used with the same interface. Each of these classes can provide its own implementation of the interface. Java supports two kinds of polymorphism. You can overload a method with different sets of parameters.

nisargshah

Polymorphism comprises of two words : Poly means "many" and morph means "forms". It means we can use multiple method names with the same class. There are two types of polymorphism : Static polymorphism and Dynamic Polymorphism.

Hope this answer helps!

https://www.yatharthmarketing.com/top-corporates-sales-consulting-programs-services-company-india-dubai-usa.html [nofollow]
https://www.yatharthmarketing.com/corporate-training-programs-mumbai-pune-bangalore-delhi-ahmedabad.html
https://www.yatharthmarketing.com/top-corporate-training-services-company.html
  •  


saravanan28

The word polymorphism means having many forms. ... Real life example of polymorphism: A person at the same time can have different characteristic. Like a man at the same time is a father, a husband, an employee. So the same person posses different behavior in different situations. This is called polymorphism.
  •  


Lishmalinyjames

Polymorphism is one of the core concepts in OOP languages. It describes the concept that different classes can be used with the same interface. Each of these classes can provide its own implementation of the interface. That is called dynamic polymorphism.