I’ve always been a little wary about polymorphism and still don’t think I understand the concept to the fullest.
I understand polymorphism as an object can take many forms. So an object can be one form then be another?
Mammal (base class) cat (subclass of mammal) supercat (subclass of cat)
Cat newCat = new Cat();
Now I want the cat to be a supercat, is this “Polymorphism”?
SuperCat supCat = (SuperCat)newCat;
Isn’t this just like casting? When do you want to use casting? Is the above line of code valid? So newCat gets transformed to Supercat, does it give newCat more memory allocation? Then copies it into supCat?
NOTE — Polymorphism is the use of interfaces?
Just a comment on your note.
There are two types of polymorphism.
Compile time polymorphism:
This is where your polymorphic behavior is defined prior to compilation.
This happens with method overloading e.g.
Runtime polymorphism:
This is where the polymorphic behavior happens at runtime.
An example of this would be a method that accepts a type that implements a specific interface (or common base class). This interface could be of a different type depending on the code that is executing.
e.g.
Now if the Warrior is given a Gun the output from Attack would be Shoot and for a Knife it would be Stab.
I haven’t tested this code so there may be syntax errors etc., but you should be able to get the idea