Polymorphism in Java is a core concept of object-oriented programming that allows objects of different classes to be treated as objects of a common superclass type.
It enables flexibility and extensibility in code by allowing methods to behave differently based on the object they are invoked on.
Polymorphism is achieved through method overriding and method overloading.
Here are the two main types of polymorphism in Java:
Method overloading allows a class to have multiple methods with the same name but different parameter lists.
The Java compiler determines which overloaded method to call based on the number and types of arguments passed to the method.
Overloaded methods can have different return types, but they must have a different number or type of parameters.
class Calculator { int add(int a, int b) { System.out.println("Calling Int Add Method"); System.out.println("a value: " + a + ", b Value: " + b); return a + b; } double add(double a, double b) { System.out.println("Calling Double Add Method"); System.out.println("a value: " + a + ", b Value: " + b); return a + b; } } public class Main { public static void main(String[] args) { // Creating instances of Calculator Calculator calculator = new Calculator(); // Calling int Add Method calculator.add(4, 5); // Calling Double Data Type Add Method calculator.add(4.0, 6.0); } }
Calling Int Add Method a value: 4, b Value: 5 Calling Double Add Method a value: 4.0, b Value: 6.0
class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { // Creating instances of Dog Dog dog = new Dog(); // Calling dog Class Sound Method dog.sound(); // Creating instances of Animal // Animal animal = new Animal(); // Calling Animal Class Sound Method // animal.sound(); } }
Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass.
The method to be executed is determined at runtime based on the actual type of the object (dynamic binding).
The "@Override" annotation is used to indicate that a method in the subclass overrides a method in the superclass.
Dog barks
Polymorphism allows for more flexible and reusable code because it allows methods to be invoked on objects without knowing their specific types at compile time.
This makes code more adaptable to change and simplifies the design of complex systems by promoting loose coupling between classes.