简体   繁体   中英

Use of run-time polymorphism

I am novice in programming, I want to ask that what is the ultimate use of run-time polymorphism?

Example:

class Parent
{
    //do something
}
class Child : Parent
{
    //do something
}

main()
{
    Parent p = new Child (); // run-time polymorphism
    Child q = new Child(); // no polymorphism
}

My question is that, we use first line ( Parent p = new Child(); ) to achieve runtime polymorphism, but we can use second line ( Child q = new Child(); ) in lieu of first one....

So what is the difference between both of them? Why do we use run-time polymorphism?

While your example shows why that is a poor example, picture something like this:

main()
{
    Parent p = Factory("SomeCondition"); ///run-time polymorphism
}

Parent Factory(string condition)
{
    if (condition == "SomeCondition")
    {
        return new Child();
    }
    else
    {
        return new Parent();
    }      
}

When the factory is called, we don't know what the return type will actually be, it could be a child, it could be a parent.

There's no actual use for the code snippet you've provided. But think about this method:

public void DoSomething( Parent parent ){ ... }

You can do this:

Child child = new Child();
DoSomething( child );

In this case, for DoSomething it will be just a Parent. It doesn't care if it is a subclass or not.

Hope it helps.

The ultimate use of run-time polymorphism is generalisation. It promotes code reuse by allowing subclasses of a common superclass to be used. You don't want to write separate methods for each object from different classes, that would get tedious.

Run-time polymorphism allows you to write generalised code which can be used by many different subclasses.

A better simple example would be something like this. Each animal may eat different food and have different logic on how to feed, but you abstract out the "how" and only care that the method follows the expect rules.

I personally think Interfaces is a great way to see the usefulness of polymorphism. Look those up.

class Pet

class Cat : Pet

class Persian : Cat

class Dog : Pet

class Chiwawa : Dog

main{
Pet myPet = new Persian();
if(myPet.IsHungry())    
myPet.feed();

myPet = new Chiwawa()

if(myPet.IsHungry())
myPet.Feed()
}

The primary use for this is not for instantiation, as you have shown, it is for processing all of the objects that inherit from a common ancestor using a single set of code.

Examples of this use include passing objects as parameters to methods or iterating over a collection of objects of different types and performing the same action on all of them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM