Polymorphism in Java is the ability of an object to take many forms. It allows the same method name to behave differently based on the object or arguments. There are two main types: compile-time (method overloading) and runtime (method overriding).
Method Overloading: Happens at compile time. Same method name but different parameter lists (number or type of arguments).
Method Overriding: Happens at runtime. A subclass provides its own implementation of a method defined in the parent class.
No, we cannot override a static method because static methods are bound at compile time (class-level), while overriding requires runtime binding (object-level). However, we can hide a static method by redefining it in the subclass.
class Calculator {
// Method overloading
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
public class OverloadingDemo {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Sum of integers: " + calc.add(5, 10));
System.out.println("Sum of doubles: " + calc.add(5.5, 10.5));
}
}
OUTPUT
Sum of integers: 15
Sum of doubles: 16.0
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
OUTPUT
Dog barks