Ask your own question, for FREE!
Computer Science 22 Online
OpenStudy (anonymous):

What are the similarities between function overloading and polymorphism? What are the differences?

OpenStudy (anonymous):

function overloading is a type of polymorphism. you cant have similarities or differences on a type and a concept i mean polymorphism is a concept and overloading is a type of it

OpenStudy (shadowfiend):

That's not entirely accurate. Both allow you to treat types differently. The big difference is that overloading typically is resolved at compile time (something we've been bitten with in our own code base), while polymorphism is resolved at runtime. Here's an example: let's say I want to find the area of a shape, and I implement it using overloading: double area(Shape shape) { return 2; /* for argument's sake */ } double area(Square square) { return square.sideLength * square.sideLength; } double area(Rectangle rectangle) { return rectangle.side1Length * rectangle.side2Length; } double area(Circle circle) { return Math.PI * Math.pow(circle.radius, 2) } Now here's the issue: Square square = new Square(35 /* radius */); Shape s = new Square(35 /* radius */); area(s); /* this will return 2 */ area(square); /* this will return 1225 */

OpenStudy (shadowfiend):

If we do this using polymorphism, the story is different: class Shape { double area() { return 2; } } class Square { double area() { return sideLength * sideLength; } } Square square = new Square(35 /* radius */); Shape s = new Square(35 /* radius */); square.area(); /* returns 1225 */ s.area(); /* returns 1225 */

OpenStudy (anonymous):

in the second example (where you had Square inherit the area member function) that's what you call method overriding, while in the first one it's function overloading?

OpenStudy (shadowfiend):

That is correct.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!