Is polymorphism possible without inheritance ?? Explain it with example, please.

18th Jul 2016, 11:44 AM
AnsHuman Aaditya
AnsHuman Aaditya - avatar
4 Answers
+ 4
function overloading is also one type of polymorphism
25th Jul 2016, 11:48 AM
Vishal Koshti
Vishal Koshti - avatar
Yeah, methods can also be polymorphic. If you want a method to perform differently depending on the parameter it receives, that is also polymorphism. You can achieve this by making more than one method with the same name but different parameters. E.g A method to calculate the area of a rectangle. You would enter 2 values for a rectangle with differing height and width but may only want to enter one value for a rectangle with equal sides (a square). public double areaRect(double x, double y){ return x*y; } public double areaRect (double x){ return x*x; } This way the functionality of te method changes depending on what parameters where entered. This applies for constructors too.
19th Jul 2016, 1:37 PM
Gershon Fosu
Gershon Fosu - avatar
hey Gershon I believe the example you have given is an example of overloading and not polymorphism. I agree the answer is yes, in polymorphism, you derive from a base class then override the the implementation in the derived class (polymorphism) so that you the derived class can specify a more specialized or different implementation by implementing the base class and usually methods that override the base class have the @override annotation whereas in inheritance you are just using the methods in your base class as is (code reuse) I.e. you extend the base class, that is your literally extend the functionality of your base class to your derived classes.
22nd Jul 2016, 3:48 AM
Eric Gitangu
Eric Gitangu - avatar
yes before you start writing any system you need to consider which approach will be the best for your application using inheritance have a lot of security problems in which you don't want to expose your work to this security risk but polymorphism takes care of the because other class can't see or have access to any of the inner workings of the class
27th Jul 2016, 7:18 AM
Paul Bereobong Clement
Paul Bereobong Clement - avatar