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?
There’s no actual use for the code snippet you’ve provided. But think about this method:
You can do this:
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.