Lesson 20 of 34

Method Overloading

7 min 30 XP

Several methods can share a name as long as their parameters differ in number or type. Java picks the right one from the call. This is compile-time polymorphism, a classic interview term.

Example: edit me and press Run

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.

Changing only the return type is not overloading; it's a compile error.

Challenge

+30 XP

Write two methods named area: area(int side) for a square and area(int l, int w) for a rectangle. In main(), read s, l and w and print both areas. Input: 4 3 5 Output: 16 15

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.