What is the difference between method overloading and overriding in Java?
| Point | Overloading | Overriding |
|---|---|---|
| Where | Same class (or subclass) | Subclass and parent class |
| Parameters | Must be different | Must be the same |
| Return type | Can be different | Same (or a subtype) |
| Decided | At compile time | At run time |
| Also called | Compile time polymorphism | Run time polymorphism |
class Animal {
void sound() { System.out.println("..."); }
}
class Dog extends Animal {
@Override
void sound() { System.out.println("Woof"); } // overriding
void sound(int times) { // overloading
for (int i = 0; i < times; i++) System.out.print("Woof ");
System.out.println();
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
new Dog().sound(2);
}
}
Output
Woof
Woof Woof
See Overloading and Inheritance.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |