0/30 Days Completed 0 Learning Days
Day 20 of 30 · Week 3 — OOPS Fundamentals
Polymorphism: overloading and overriding
1 Learn
Polymorphism means "many forms": the same method name can behave differently.
Overloading: same method name in one class with different parameter lists. Java chooses at compile time.
Overriding: a subclass provides its own version of a parent method with the same signature. Java chooses at run time, based on the actual object.
2 See the Code
Java
class Shape {
void draw() { System.out.println("Drawing a shape"); }
}
class Circle extends Shape {
@Override
void draw() { System.out.println("Drawing a circle"); }
}
public class Art {
static int area(int side) { return side * side; }
static int area(int l, int w) { return l * w; }
public static void main(String[] args) {
System.out.println(area(4));
System.out.println(area(3, 5));
Shape s = new Circle();
s.draw();
}
}- area(int) and area(int, int) are overloaded.
- Circle overrides draw(). Even though s is a Shape variable, the object is a Circle, so the Circle version runs.
Output
16 15 Drawing a circle
3 Practice
- Overload a method greet() and greet(String name). Then override speak() in a Cat class.
Try it in your own Java setup or write it in the Practice Notebook.
4 Quick Check
1. Overloading means...
2. Shape s = new Circle(); s.draw(); runs whose draw?
Step 5
Answer and check the Quick Check above to unlock this.