Polymophism

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 Illustration Polymorphism: A person at the same time can have different characteristics. Like a man at the same time is a father, a husband, and an employee. So the same person possesses different behavior in different situations. This is called polymorphism.

Polymorphism is considered one of the important features of Object-Oriented Programming. Polymorphism allows us to perform a single action in different ways. In other words, polymorphism allows you to define one interface and have multiple implementations. The word “poly” means many and “morphs” means forms, So it means many forms.

Example of Polymorphism

using System;
class Program
{
    // method does not take any parameter 
    public void greet()
    {
        Console.WriteLine("Hello");
    }

    // method takes one string parameter
    public void greet(string name)
    {
        Console.WriteLine("Hello " + name);
    }

    static void Main(string[] args)
    {
        Program p1 = new Program();

        // calls method without any argument
        p1.greet();

        //calls method with an argument
        p1.greet("Tim");

    }
}

Output

Hello
Hello Tim

In the above example, we have created a class Program inside which we have two methods of the same name greet().

Here, one of the greet() methods takes no parameters and displays "Hello". While the other greet() method takes a parameter and displays "Hello Tim".

Hence, the greet() method behaves differently in different scenarios. Or, we can say greet() is polymorphic.

Types of Polymorphism

There are two types of polymorphism:

  1. Compile Time Polymorphism / Static Polymorphism

  2. Run-Time Polymorphism / Dynamic Polymorphism

I. Compile-Time Polymorphism

It is also known as static polymorphism. This type of polymorphism is achieved by function overloading or operator overloading.

Note: But Java doesn’t support the Operator Overloading.

Method Overloading

When there are multiple functions with the same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by changes in the number of arguments or/and a change in the type of arguments.

Example 1:

// Java Program for Method overloading
// By using Different Types of Arguments

// Class 1
// Helper class
class Helper {

	// Method with 2 integer parameters
	static int Multiply(int a, int b)
	{

		// Returns product of integer numbers
		return a * b;
	}

	// Method 2
	// With same name but with 2 double parameters
	static double Multiply(double a, double b)
	{

		// Returns product of double numbers
		return a * b;
	}
}

// Class 2
// Main class
class GFG {

	// Main driver method
	public static void main(String[] args)
	{

		// Calling method by passing
		// input as in arguments
		System.out.println(Helper.Multiply(2, 4));
		System.out.println(Helper.Multiply(5.5, 6.3));
	}
}

Output

8
34.65
// Java program for Method Overloading
// by Using Different Numbers of Arguments

// Class 1
// Helper class
class Helper {

	// Method 1
	// Multiplication of 2 numbers
	static int Multiply(int a, int b)
	{

		// Return product
		return a * b;
	}

	// Method 2
	// // Multiplication of 3 numbers
	static int Multiply(int a, int b, int c)
	{

		// Return product
		return a * b * c;
	}
}

// Class 2
// Main class
class GFG {

	// Main driver method
	public static void main(String[] args)
	{

		// Calling method by passing
		// input as in arguments
		System.out.println(Helper.Multiply(2, 4));
		System.out.println(Helper.Multiply(2, 7, 3));
	}
}

Output

8
42

C# Method Overloading

In a C# class, we can create methods with the same name in a class if they have:

  • different numbers of parameter

  • types of parameter

For example,

void totalSum() {...}
void totalSum(int a) {...}
void totalSum(int a, int b) {...}
void totalSum(float a, float b) {...}

Here we have different types and numbers of parameters in totalSum(). This is known as method overloading in C#. The same method will perform different operations based on the parameter.

Look at the example below,

using System;
class Program
{

    // method adds two integer numbers
    void totalSum(int a, int b)
    {
        Console.WriteLine("The sum of numbers is " + (a + b));
    }

    // method adds two double-type numbers
    // totalSum() method is overloaded
    void totalSum(double a, double b)
    {
        Console.WriteLine("The sum of numbers is " + (a + b));
    }
    static void Main(string[] args)
    {

        Program sum1 = new Program();
        sum1.totalSum(5, 7);
        sum1.totalSum(53.5, 8.7);
    }
}

Output

The sum of numbers is 12
The sum of numbers is 62.2

In the above example, the class Program contains a method named totalSum() that is overloaded. The totalSum() method prints:

  • sum of integers if two integers are passed as an argument

  • sum of doubles if two doubles are passed as an argument

2. C# Operator Overloading

Some operators in C# behave differently with different operands. For example,

  • + operator is overloaded to perform numeric addition as well as string concatenation and

Now let's see how we can achieve polymorphism using operator overloading.

The + operator is used to add two entities. However, in C#, the + operator performs two operations:

1. Adding two numbers,

int x = 7;
int y = 5;
int sum = x + y;
Console.WriteLine(sum);
// Output: 12

2. Concatenating two strings,

string firstString = "Harry";
string secondString = "Styles";

string concatenatedString = firstString + secondString;
Console.WriteLine(concatenatedString);
// Output: HarryStyles

Here, we can see that the + operator is overloaded in C# to perform two operations: addition and concatenation.

II. Runtime Polymorphism

It is also known as Dynamic Method Dispatch. It is a process in which a function call to the overridden method is resolved at Runtime. This type of polymorphism is achieved by Method Overriding. Method overriding, on the other hand, occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.

Example

// Java Program for Method Overriding

// Class 1
// Helper class
class Parent {

	// Method of parent class
	void Print()
	{

		// Print statement
		System.out.println("parent class");
	}
}

// Class 2
// Helper class
class subclass1 extends Parent {

	// Method
	void Print() { System.out.println("subclass1"); }
}

// Class 3
// Helper class
class subclass2 extends Parent {

	// Method
	void Print()
	{

		// Print statement
		System.out.println("subclass2");
	}
}

// Class 4
// Main class
class GFG {

	// Main driver method
	public static void main(String[] args)
	{

		// Creating object of class 1
		Parent a;

		// Now we will be calling print methods
		// inside main() method

		a = new subclass1();
		a.Print();

		a = new subclass2();
		a.Print();
	}
}

Output

subclass1
subclass2

Explanation of the above code:

Here in this program, When an object of a child class is created, then the method inside the child class is called. This is because The method in the parent class is overridden by the child class. Since The method is overridden, This method has more priority than the parent method inside the child class. So, the body inside the child class is executed.

Virtual functions

It allows an object of a derived class to behave as if it were an object of the base class. The derived class can override the virtual function of the base class to provide its own implementation. The function call is resolved at runtime, depending on the actual type of the object.

Polymorphism in Java is a concept that allows objects of different classes to be treated as objects of a common class. It enables objects to behave differently based on their specific class type.

Method Overriding in C#

During inheritance in C#, if the same method is present in both the superclass and the subclass. Then, the method in the subclass overrides the same method in the superclass. This is called method overriding.

In this case, the same method will perform one operation in the superclass and another operation in the subclass.

We can use virtual and override keywords to achieve method overriding.

Let's see the example below,

using System;
class Polygon
{
    // method to render a shape
    public virtual void render()
    {
        Console.WriteLine("Rendering Polygon...");
    }
}

class Square : Polygon
{
    // overriding render() method 
    public override void render()
    {
        Console.WriteLine("Rendering Square...");
    }
}
class myProgram
{
    public static void Main()
    {
        // obj1 is the object of Polygon class
        Polygon obj1 = new Polygon();

        // calls render() method of Polygon Superclass 
        obj1.render();

        // here, obj1 is the object of derived class Square 
        obj1 = new Square();

        // calls render() method of derived class Square
        obj1.render();
    }
}

Output

Rendering Polygon...
Rendering Square…

In the above example, we have created a superclass: Polygon and a subclass: Square.

Notice, we have used virtual and override with methods of the base class and derived class respectively. Here,

  • virtual - allows the method to be overridden by the derived class

  • override - indicates the method is overriding the method from the base class

In this way, we achieve method overriding in C#.

Note: A method in derived class overrides the method in base class if the method in derived class has the same name, same return type and same parameters as that of the base class.

Advantages of Polymorphism

  1. Increases code reusability by allowing objects of different classes to be treated as objects of a common class.

  2. Improves readability and maintainability of code by reducing the amount of code that needs to be written and maintained.

  3. Supports dynamic binding, enabling the correct method to be called at runtime, based on the actual class of the object.

  4. Enables objects to be treated as a single type, making it easier to write generic code that can handle objects of different types.

Disadvantages of Polymorphism

  1. Can make it more difficult to understand the behavior of an object, especially if the code is complex.

  2. This may lead to performance issues, as polymorphic behavior may require additional computations at runtime.

Last updated