DEV Community

Cover image for what is polymorphism in computer science ?
betpido
betpido

Posted on

what is polymorphism in computer science ?

Polymorphism is a fundamental concept in object-oriented programming (OOP) that describes situations in which something occurs in several different forms.

In computer science, polymorphism allows objects of different classes to be treated as objects of a common class.

This enables objects to behave differently based on their specific class type, increasing code reusability by allowing objects of different classes to be treated as objects of a common class.

Polymorphism can be classified into two types: static or compile-time and dynamic or runtime.

Static polymorphism is achieved through method overloading, while dynamic polymorphism is achieved through method overriding.

In summary, polymorphism is a powerful tool that allows developers to write more efficient and reusable code by enabling objects of different classes to be treated as objects of a common class.

An example of polymorphism in Java:

class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}

class Dog extends Animal {
public void makeSound() {
System.out.println("The dog barks");
}
}

class Cat extends Animal {
public void makeSound() {
System.out.println("The cat meows");
}
}

public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal();

Animal myDog = new Dog();

Animal myCat = new Cat();

myAnimal.makeSound();
myDog.makeSound();
myCat.makeSound();
Enter fullscreen mode Exit fullscreen mode

}
}
In this example, we have a base class called Animal and two derived classes called Dog and Cat.

The Dog and Cat classes inherit from the Animal class and override the makeSound() method.

The makeSound() method is then called on objects of each class. When the makeSound() method is called on the myAnimal object, the output is “The animal makes a sound”.

When the same method is called on the myDog object, the output is “The dog barks”. Similarly, when the same method is called on the myCat object, the output is “The cat meows”.

This demonstrates how polymorphism allows objects of different classes to be treated as objects of a common class

Top comments (0)