I would like to know how does JVM differentiates between method overloading and method overriding internally.
Overriding occurs when the method signature is the same in the superclass and the child class. Overloading occurs when two or more methods in the same class have the same name but different parameters.
In method overloading, methods must have the same name and different signatures. In method overriding, methods must have the same name and same signature.
The JVM only deals with method overriding. A method is overridden by adding a method with the same signature in a derived class (the only allowed difference is in the return type, which is allowed to be more specific). The signature encodes the method's name, as well as the types of the parameters and the return type.
Method overloading means having multiple methods with the same "simple name" but different signatures. At compile time, the javac
compiler chooses one of the same-named methods based on the types of the arguments and places its signature in the compiled .class
file. A method invocation in compiled Java bytecode must specify the signature of the callee.
Jvm in not involved in method overloading. So it does not have to differentiate between method overloading and method overriding.
You would understand this clearly if you understand how method overloading and method overriding is implemented by Java behind the scenes.
Before going into the difference between overloading and overriding , let us first take a look into Polymorphism .
What is polymorphism ?
Polymorphism is the capability of a method to do different things based on the object that it is acting upon. In other words, polymorphism allows you define one interface and have multiple implementations.
Different types of polymorphism in java. 1) Method Overloading 2) Method Overriding
Types of polymorphism in java: Static, Dynamic, Runtime and Compile time
Now let us come back to the original question and understand the difference between overloading and overriding.
1. The first and most important is that method overloading a compile time polymorphism while method overriding is run time polymorphism. So JVM has to only deal with method overriding . Method overloading is already resolved after compilation.
2.In Method Overloading, methods must have different signature.In Method Overriding, methods must have same signature.
There are many more differences, but above two can really differentiate method overloading from method overriding.
Before winding up let us also look at what each is trying to achieve .
Method Overloading is to “add” or “extend” more to method’s behavior.Method Overriding is to “Change” existing behavior of method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With