Eslam Hamdy
Eslam Hamdy

Reputation: 7386

why polymorphism doesn't matters when a method is overloaded?

i know that overloaded methods are determined at compile time based on the reference type which invokes the method while overrided methods is determined by the actual object type of the reference invoking he method, the question is why polymorphism only matters about overriding and not overloading?

Upvotes: 0

Views: 308

Answers (4)

Marko Topolnik
Marko Topolnik

Reputation: 200138

The implementation mechanism that makes polymorphism in Java possible is the dynamic dispatch of a method based on the runtime type of its first argument (in a call a.method(b, c), a can be considered the first argument of the method). Java is therefore a single dispatch OOP language. The upshot is that all other arguments don't participate in this mechanism and their type is determined statically at compile time. So for example if you have

class MyObject {
  public boolean equals(MyObject o) { ... }
}

and then

MyObject m1 = new MyObject();
Object o = new MyObject();
System.out.println(m1.equals(o));

can never print true since your method is not being called. The compiler saw a call MyObject.equals(Object) and compiled it as a call of the inherited method Object.equals(Object). The runtime method dispatch mechanism will only decide which overriding method equals(Object) to call.

Upvotes: 2

Cratylus
Cratylus

Reputation: 54074

You are confused on this.
Overloading refers to selecting one of the methods having the same name but different signature in the same class (not hierarchy).
Overriding is chose among methods of the same name depending on the runtime type among those inherited by parent classes.
If you have a base class and a derived class with a method of the same name and signature then this is overriding and at runtime the correct is determined.

For overloading the compiler picks the correct version of method to use, among the available in the same class.
No need to find a runtime type. Compiler can figure this out at compile time

Upvotes: 0

Ozan
Ozan

Reputation: 4415

This is for technical reasons. Usually only the this pointer, as hidden first parameter of the method, is analyzed at runtime to determine the method to be called.

When other parameters, too, are analyzed it is called Multiple Dispatch. There are a few languages that support multiple dispatch natively.

Upvotes: 0

Bhaskar
Bhaskar

Reputation: 7523

polymorphism , as the name implies , is when a method "of the same form" manifests different behaviours under different contexts. The term "same form" means "same signature". That implies you cannot relate polymorphism with overloaded methods because they have "different forms" to begin with. Another way to think about it is - you need a type and a subtype to see polymorphism in action - overloaded methods again are defined in the context of a single class.

Upvotes: 0

Related Questions