Abstract
- Method overloading happens when multiple methods in the same class (or inherited from a parent class) that share the same name but have different parameters (different function signature). You create an overloaded method by changing the types, order, or number of parameters the method takes, while keeping the method name the same
Why is this useful?
This allows the class to provide different implementations for the same conceptual operation based on the input it receives, promoting Polymorphism.
However, method overloading is not considered a form of polymorphism. Polymorphism involves providing different implementations to an existing method descriptor defined in a parent class or interface!
Not about changing the names of the parameters
Overloading is about changing the order, number, or types of parameters.
Method overriding in Java
You can even overload Java Constructor!
You can also overload static methods the same way you overload instance methods!
Method Invocation
- Java favours the “more specific” method when there are multiple methods with the same name but different function signature
What is more specific?
A method
Mis more specific than a methodNif the arguments toMcan be passed toNwithout a compilation error.For example,
equals(Circle)is more specific thanequals(Object)because aCircleobject can be passed toequals(Object)without a compilation error.Another example,
equals(int)is more specific thanequals(double)because anintvalue can be passed toequals(double)without a compilation error due to automatic widening conversion. However, adoublevalue cannot be passed toequals(int)without a compilation error because it would require an explicit narrowing conversion.
