Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why to use Polymorphism?

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?

like image 238
baig772 Avatar asked Jun 16 '12 14:06

baig772


People also ask

Why you should use polymorphism?

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.

What is polymorphism and why do we use it?

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.

Why do we use polymorphism in Java?

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.


1 Answers

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.

like image 159
Tim Pote Avatar answered Sep 24 '22 06:09

Tim Pote