Java Java Tutorial Java Methods Java Classes Java File Handling Java Reference



Java Polymorphism

Polymorphism is one of the fundamental concepts in object-oriented programming. It allows objects of different classes to be treated as if they were objects of the same class. Java supports two types of polymorphism: compile-time polymorphism and runtime polymorphism.

Compile-time Polymorphism

Compile-time polymorphism is also known as method overloading. It allows a class to have multiple methods with the same name but different parameters. The compiler determines which method to call based on the number and types of arguments passed to the method.

Here is an example of method overloading:


public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

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

Calculator calculator = new Calculator();
int result1 = calculator.add(1, 2);
double result2 = calculator.add(1.5, 2.5);

In this example, the Calculator class has two methods with the same name "add", but one takes two integers as arguments and the other takes two doubles. The compiler determines which method to call based on the types of arguments passed to the method.

Runtime Polymorphism

Runtime polymorphism is also known as method overriding. It allows a subclass to provide its own implementation of a method that is already defined in its superclass. The subclass method must have the same name, return type, and parameters as the superclass method.

Here is an example of method overriding:


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

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

Animal animal = new Dog();
animal.makeSound();

In this example, the Animal class has a method called "makeSound". The Dog class extends the Animal class and overrides the "makeSound" method with its own implementation. When an object of the Dog class is created and assigned to a variable of type Animal, the "makeSound" method of the Dog class is called instead of the "makeSound" method of the Animal class.

Conclusion

Polymorphism is a powerful concept in object-oriented programming that allows for code reuse and flexibility. Java supports both compile-time polymorphism and runtime polymorphism, which can be used to create more efficient and maintainable code.

References

Activity