Polymorphism in Greek means having multiple forms. The ancient Greek culture was polytheistic society meaning that they worshiped multiple gods. In today’s object oriented programming we use this same concept to develop modular generic methods and classes.
Polymorphism allows objects to be accessed by their current data types or base data types from which the object inherit called interfaces. An interface provides common functionality between all of its derived classes.
// Objects derived from the class Person
Doctor _p1 = new Doctor(“Bill”);
Lawyer _p2 = new Lawyer(“Larry”);
Cook _p3 = new Cook(“Chuck”);
Bumb _p4 = new Bumb(“Bart”);
Person contains the following methods:
The variable xperson is used to interface with all the created objects listed above with access to only the methods that are defined in the Person class. This allows for a generic design because any derived object of the class Person can be assigned to the person interface making it accessible.
Xperson = _p1;
Console.writeline(Xperson.name); // writes Bill
Xperson = _p2;
Console.writeline(Xperson.name); // writes Larry
Xperson = _p3;
Console.writeline(Xperson.name); // writes Chuck
Xperson = _p4;
Console.writeline(Xperson.name); // writes Bart
Because Person is the base class of all 4 of the objects listed above it has full access to use any method in these classes that is also defined in the base class.