Polymorphism
Poly means many, morph means forms. Polymorphism means the same method name can perform different behaviours.
- Same method name.
- Different behaviour depending on the object or the inputs.
Real World Example: Employee
Example: EmployeeDifferent employees perform work() differently.
Employee: work()Developer: work() โ Write CodeDesigner: work() โ Create Designs
Same method: work(). Different behaviour for each employee type.
Method Overriding
Child class gives its own behaviour for an inherited method, this is called overriding.
Code Exampleclass Employee {
public void work() {
System.out.println("Working...");
}
}
class Developer extends Employee {
@Override
public void work() {
System.out.println("Writing code");
}
}
Developer keeps the same work() name as Employee but replaces what it does.
- Same method:
work() - Different behaviour: Writing code
Method Overloading
Same method name with different parameters, this is called overloading.
Code Exampleclass Employee {
public void work() {
System.out.println("Working...");
}
public void work(int hours) {
System.out.println("Working " + hours + " hours");
}
}
Java picks the right version of work() based on what arguments are passed in.
work()work(5)- Same method name, different inputs.
Class Diagram
โโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Employee โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ +work(): void โ
โ +work(int): void โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโ
โฒ
โ extends
โโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Developer โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ +work(): void โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโ
Employee shows overloading (work() and work(int) side by side). Developer extending Employee and replacing work() shows overriding.
Key Idea: Polymorphism = One Name, Many Forms.
- Overloading: same method, different parameters.
- Overriding: same method, different behaviour.
Exam Focus Points
- Polymorphism lets one method name behave differently depending on the object or the arguments used.
- Overloading happens in the same class: same name, different parameter lists.
- Overriding happens between parent and child classes: same name and parameters, different implementation, using
@Override.
Summary
- Polymorphism means one method name can take many forms.
- Method overloading defines multiple versions of a method in the same class, distinguished by their parameters.
- Method overriding lets a child class replace a method it inherited from its parent class.
- Polymorphism = One Name, Many Forms.