Reputation: 3278
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?
Upvotes: 1
Views: 1880
Reputation: 1035
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()
}
Upvotes: 1
Reputation: 2164
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.
Upvotes: 1
Reputation: 44941
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.
Upvotes: 0
Reputation: 12614
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.
Upvotes: 5
Reputation: 8362
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.
Upvotes: 4