In this post, we will learn the difference between Method Overloading and Method Overriding in Java. This is a frequently asked question in Java interviews for beginners. Let's dive into it.
Difference between Method Overloading and Method Overriding in Java
Features | Method Overloading | Method Overriding |
---|---|---|
Definition | When a class has more than one method with the same name but with different arguments, then it's called method overloading. | When a superclass method is modified in the subclass, then it's called method overriding. |
Method Signatures | Overloaded methods must differ in number of arguments, types of arguments, or order of arguments. But, they must have the same name. | Overridden methods must have the same method signature. You must not change the method name, types of arguments, number of arguments, and order of arguments while overriding a superclass method. |
Return Types | Overloaded methods can have the same or different return types. | The return type of the overridden method must be compatible with that of the superclass method. If the superclass method has a primitive type as its return type, then it must be overridden with the same return type. If the superclass method has a derived type as its return type then it must be overridden with the same type or its subclass type. |
Visibility | Overloaded methods can have the same visibility or different visibility. | While overriding a superclass method either you can keep the same visibility or you can increase the visibility. But you can’t reduce it. |
Static Methods | Overloaded methods can be static or not static. It does not affect the method overloading. | You can’t override a static method. |
Binding | Binding between method call and method definition happens at compile time (Static Binding). | Binding between method call and method definition happens at run time (Dynamic Binding). |
Polymorphism | It shows static polymorphism. | It shows dynamic polymorphism. |
Private Methods | Private methods can be overloaded. | Private methods can’t be overridden. |
Final Methods | Final methods can be overloaded. | Final methods can’t be overridden. |
Required Classes | For method overloading, only one class is required. Method overloading happens within a class. | For method overriding, two classes are required – superclass and subclass. That means method overriding happens between two classes. |
Interview Questions
Java
X vs Y
Comments
Post a Comment