Home page

Monday, August 7, 2023

Difference between method overloading and overriding in JAVA

Method Overloading vs. Method Overriding

Aspect Method Overloading Method Overriding
Purpose Provide multiple versions of a method in the same class based on different parameter lists. Provide a specific implementation of a method in a subclass that is already defined in its superclass.
Inheritance Occurs within the same class. Occurs between a superclass and its subclass.
Method Signature Method names must be the same, but parameter lists must be different (type, number, or order). Method names, return types, and parameter lists must be the same.
Compile-time Resolution Determined at compile time based on method signature and parameter types. Determined at runtime based on the actual object's type (dynamic polymorphism).
Return Type Overloading can have the same or different return types. Overriding must have the same return type (or covariant return type in the case of inheritance).
Access Modifiers Can have different access modifiers. Can have the same or less restrictive access modifiers (cannot be more restrictive).
Exceptions Can have different checked and unchecked exceptions. Cannot throw broader checked exceptions (but can throw narrower or unchecked exceptions).
Static vs. Instance Can involve both static and instance methods. Involves only instance methods (static methods are hidden, not overridden).
Polymorphism Not related to polymorphism. Fundamental for achieving polymorphism and runtime behavior.

No comments:

Post a Comment