In the source code, you always perform simple inheritance without any polymorphic behavior. You always instantiate a derived class and assign it to an instance variable of the derived class.
DerivedClass d = new DerivedClass(); // here no polymorphism, and only inheritance is there
So, when you call a method using a class variable, it will always call the DerivedClass method, regardless of whether this method is virtual or not in the parent class.
In polymorphism, your programs do not know the exact type of class on which you are calling the method (this concept is called late binding). As shown in the example below:
BaseClass b = new DerivedClass(); // here b is a base class instance but initiated using derived class
After calling b.method (), it will perform late binding and show polymorphic behavior (only if this method was set virtual in the base class)
NOTE. The virtual keyword delays the binding to the correct version of the method at runtime and is the key key to implementing polymorphism. Therefore, for precise polymorphic behavior, declare the methods as virtual in the parent class, and then in the child class, ovverride this method.
Irfan source share