Is method overloading a form of polymorphism or so

2019-06-28 06:58发布

问题:

I have a long standing doubt. Could someone please tell me whether method overloading is a form of polymorphism or is it something completely different?

回答1:

Method overloading is just a syntax sugar allowing you to have methods with same name but different arguments. It has nothing to do with polymorphism. Method overloading is typically used to define two methods accepting different arguments, e.g.:

public void println(boolean x) //...
public void println(char x) //...

or to skip certain parameters and use some defaults:

public String substring(int beginIndex) //...
public String substring(int beginIndex, int endIndex) //...

Method overriding, on the other hand, is a foundation of inheritance and is more closely related to polymorphism.



回答2:

Polymorphism, literally means something which has multiple behavior.

In java, we can have a static and runtime polymorphism.

Overloading is static polymorphism since it allows different behavior by means of passing varying arguments. But this is resolved at the complile time only, hence static.

Overriding, is dynamic polymorphism since the actual call to the function depends on the type of object invoking it which is available only at the runtime, hence dynamic.



回答3:

No, it is not.

With overloading you just provide different implementations of a same method name with different signatures.

Since polymorphism (by subtyping) requires the same signature (that is made either by method name either by parameters) then the two things can never intersect.



回答4:

No, its not, it's method overloading.

java does polymorphism via interfaces. It has no multiple inheritance.

You can, however, simulate multiple inhertance by using multiple interface and the composite/delegate pattern.



回答5:

No it's not related to object oriented programming. Overloading simply means that you can use the same name for different method signatures.