Polymorphism is a fundamental concept in object-oriented programming that allows objects to take on many forms.
In Java, polymorphism refers to the ability of a variable, object, or method to take on different forms depending on the context in which it is used. This allows different objects to be treated as if they were of the same type, and for different methods to be called depending on the actual type of the object.
There are two types of polymorphism in Java
Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. The subclass's method overrides the superclass's method. It is resolved at runtime and hence known as runtime polymorphism.
final in the parent class cannot be overridden in the child class. The final keyword prevents a method from being modified in any subclass.public method in the parent class cannot be overridden as private in the child class.@Override annotation is used to indicate that a method is overriding a method from the superclass. This is optional but recommended for better readability and error prevention.super Keyword: The super keyword can be used within the child class method to call the method of the parent class. This is useful when you want to extend the functionality of the parent class method rather than completely replace it.// Achieving Polymorphism through Overridingclass Animal { public void makeSound() { System.out.println("This 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 TestPolymorphism { public static void main(String[] args) { Animal myAnimal; // Reference variable of type Animal myAnimal = new Dog(); // Dog object myAnimal.makeSound(); // Calls the overridden method in Dog class myAnimal = new Cat(); // Cat object myAnimal.makeSound(); // Calls the overridden method in Cat class }}The dog barks.
The cat meows.
Method overloading allows a class to have more than one method with the same name, provided their parameter lists are different. It is resolved at compile-time and hence known as compile-time polymorphism.
xxxxxxxxxxpublic class MathUtils { // Method to add two integers public int add(int a, int b) { return a + b; } // Method to add three integers public int add(int a, int b, int c) { return a + b + c; } // Method to add two double numbers public double add(double a, double b) { return a + b; } public static void main(String[] args) { MathUtils utils = new MathUtils(); System.out.println("Sum of 2 integers: " + utils.add(1, 2)); // Calls the first method System.out.println("Sum of 3 integers: " + utils.add(1, 2, 3)); // Calls the second method System.out.println("Sum of 2 doubles: " + utils.add(1.5, 2.5)); // Calls the third method }}Sum of 2 integers: 3
Sum of 3 integers: 6
Sum of 2 doubles: 4.0