π What is Polymorphism?
Polymorphism literally means "many forms". In Java, it allows objects to take on multiple forms depending on the context.
In other words:
- A single interface can be used to represent different underlying forms (data types).
π― Why Use Polymorphism?
Polymorphism makes your code:
- More flexible
- Easier to extend
- Cleaner and more readable
π What is Method Overriding in Java?
Method Overriding happens when a subclass (child class) provides a specific implementation of a method that is already defined in its superclass (parent class).
Key Points:
- Method must have same name, same return type, and same parameters. -Used for runtime polymorphism. -Allows a subclass to provide a custom behavior for a method inherited from the parent class.
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
π What is Method Overloading in Java?
Method Overloading means having multiple methods in the same class with the same name but different parameters (number or type).
Key Points:
- Happens within the same class.
- Used for compile-time polymorphism.
- Helps in increasing the readability of the program.
Example:
class MathUtils {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}