0
Is polymorphism possible without inheritance ?? Explain it with example, please.
4 ответов
+ 4
function overloading is also one type of polymorphism
0
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.
0
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.
0
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