Polymorphism is a core concept in object-oriented programming that allows objects to be treated as instances of their parent class or as instances of their own class. It enables methods to behave differently based on the actual object type, providing flexibility and extensibility in code. In Java, polymorphism is achieved through method overriding and method overloading. Here's an overview of Java polymorphism:
Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. The subclass can provide its own implementation of the method, which is called instead of the superclass method when invoked on an object of the subclass.
Example:
class Animal { void makeSound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { @Override void makeSound() { System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Animal animal = new Dog(); // Polymorphism: Dog object treated as Animal animal.makeSound(); // Output: Dog barks } }
Method overloading occurs when a class has multiple methods with the same name but different parameter lists. Java determines which method to call based on the number and type of arguments passed to it. This allows methods to perform similar tasks with different input parameters.
Example:
class Calculator { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } } public class Main { public static void main(String[] args) { Calculator calc = new Calculator(); System.out.println(calc.add(2, 3)); // Output: 5 System.out.println(calc.add(2.5, 3.5)); // Output: 6.0 } }
In Java, method invocation is resolved at runtime based on the actual object type rather than the reference type. This is known as dynamic binding or late binding. It allows objects to exhibit polymorphic behavior, where the correct method implementation is determined dynamically at runtime.