Polymorphism in Java

Mannan Ul Haq
0

Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows us to perform a single action in different ways. In Java, polymorphism is achieved through two main mechanisms: method overloading (compile-time polymorphism) and method overriding (runtime polymorphism).

1. Compile-Time Polymorphism (Static Polymorphism):

Compile-time polymorphism in Java is achieved through method overloading. Method overloading allows you to define multiple methods with the same name but with a different number of parameters or different types of parameters. The correct method will be determined by the argument list at compile time.


Example of function overloading:


class Main
{
    static int add(int a, int b)
    {
        return a + b;
    }

    static double add(double a, double b)
    {
        return a + b;
    }

    public static void main(String[] args)
    {
        System.out.println(add(2, 3));     // Output: 5
        System.out.println(add(2.0, 3.0)); // Output: 5.0
    }
}


In this example, the `add` method is overloaded to handle both integer and floating-point arguments. The appropriate version of the method is selected based on the argument types at compile time.


2. Runtime Polymorphism (Dynamic Polymorphism):

Runtime polymorphism in Java is achieved through method overriding and the use of an interface or a superclass reference to refer to subclass objects.


Method overriding allows a subclass to provide a specific implementation for a method that is already provided by its superclass. The decision about which method should be invoked is determined at runtime based on the actual type of the object, not the reference type.

Example of method overriding:


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

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

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

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

        myAnimal.makeSound(); // Output: The animal makes a sound
        myCat.makeSound();    // Output: The cat meows
        myDog.makeSound();    // Output: The dog barks
    }
}


In this example, we have a super class `Animal` and two sub classes `Dog` and `Cat`. Each sub class overrides the `makeSound()` method of the super class. When the method is called, the JVM checks the type of the object the method is called upon and executes the appropriate method.


Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !