Difference between method overloading method overriding
Answer : Please have difference below :
Method overloading | Method Overriding |
Method overloading can be done in same class or child class | Method Overriding can only be done if Parent child relationship exists |
If two or more methods within the same class or child class that share the same name, as long as their parameter declarations are different then methods are said overloaded (Please note return type of the method does not matter JVM will match only method name with their parameter) | In parent child class hierarchy if a method in a child class has the same name and type signature as a method in its superclass, then the method in the child class is said to override the method in the superclass. (Please note method return type should also same for method overriding) |
The overriding method can throw any exceptions that may not be thrown by the overloaded method | The overriding method may not throw any exceptions that may not be thrown by the overridden method otherwise you will see compile time exception ( Exception is not compatible with throws clause in overriding method name ) |
Overloaded methods can be call using instance of the class | If overridden method is called from within the child class it will refer to the version of that method defined in the child class. The version of the method defined by the superclass will be hidden. User super to call superclass method |
static method can be overloaded | static method can’t be overridden because parent class methods that are static will not be part of a child class although they will be accessible. If you add another static method in subclass which is identical to the one in its parent class then this subclass static method is unique and distinct from the static method in its parent class. (Please note static method are class level methods and always unique) |
Example java class:
public class OverloadAndOverrideTest extends Parent { public static void main(String[] args) throws Exception { OverloadAndOverrideTest overloadAndOverrideTest = new OverloadAndOverrideTest(); overloadAndOverrideTest.method(); overloadAndOverrideTest.method("Java Honk"); overloadAndOverrideTest.method(10); } // overrides Parent.method void method() { System.out.println("Child method"); // call super class method super.method(); } // Overload method for one String parameter. void method(String name) throws Exception { System.out.println("name: " + name); } // Overload method for one integer parameter. void method(int a) throws RuntimeException { System.out.println("a: " + a); } } class Parent { void method() { System.out.println("Parent method"); } }
Output: