I have the following code in which I have a parent class and its child. I am trying to determine how the code benefits from using polymorphism.
class FlyingMachines { public void fly() { System.out.println("No implementation"); } } class Jet extends FlyingMachines { public void fly() { System.out.println("Start, Taxi, Fly"); } public void bombardment() { System.out.println("Throw Missile"); } } public class PolymorphicTest { public static void main(String[] args) { FlyingMachines flm = new Jet(); flm.fly(); Jet j = new Jet(); j.bombardment(); j.fly(); } }
What is the advantage of polymorphism when both flm.fly()
and j.fly()
give me the same answer?
Polymorphism is one of the main features of object-oriented programming. Polymorphism in C++ allows us to reuse code by creating one function that's usable for multiple uses. We can also make operators polymorphic and use them to add not only numbers but also combine strings.
One of the core concepts of OOP or object-oriented programming, polymorphism describes situations in which a particualr thing occurs in different forms. In computer science, polymorphism describes a concept that allows us to access different types of objects through the same interface.
Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance. Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks.
In your example, the use of polymorphism isn't incredibly helpful since you only have one subclass of FlyingMachine
. Polymorphism becomes helpful if you have multiple kinds of FlyingMachine
. Then you could have a method that accepts any kind of FlyingMachine
and uses its fly()
method. An example might be testMaxAltitude(FlyingMachine)
.
Another feature that is only available with polymorphism is the ability to have a List<FlyingMachine>
and use it to store Jet
, Kite
, or VerySmallPebbles
.
One of the best cases one can make for using polymorphism is the ability to refer to interfaces rather than implementations.
For example, it's better to have a method that returns as List<FlyingMachine>
rather than an ArrayList<FlyingMachine>
. That way, I can change my implementation within the method to a LinkedList
or a Stack
without breaking any code that uses my method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With