1. Polymorphism
• Poly means Many.
• Morph means to change shape
• In programming polymorphism means changing behavior of methods
• Polymorphic methods have the same signature, that is, the name and
parameters are the same
• The methods are in different classes but related through inheritance
Class Card {
protected double amount;
protected double discount;
public virtual double Discount() {
discount = amount * 0.01;
}
}
Class GoldCard : Card {
:
public override double Discount() {
discount = amount * 0.05;
}
}
Saifut
1
2. Polymorphism
• Card Class is a base class Gold Class is Derived from Card
• Card has a method Discount() Gold’s Discount() method has same signature
• Discount() method has a default Discount() method can override or replace the
implementation default implementation and give its’ own
• The word virtual indicates that this The word override indicates that the method
method is Virtual wants to change the implementation/behavior
Saifut
2
Class Card {
protected double amount;
protected double discount;
public virtual int Discount() {
discount = amount * 0.01;
}
Class GoldCard : Card {
public override int Discount() {
discount = amount * 0.05;
}
3. Polymorphism
• Let us look at a complete example of using Polymorphism
The program is an air line baggage information application. The
program asks the user to select the type of ticket they are interested in
and provides information about how many bags and weight per bag is
allowed for that type of ticket. The design is shown below:
Saifut
3
4. Polymorphism
Out put of the program when each radio button is selected followed by
clicking the purchase button
The classes and code behind the button is given in the next slides
Saifut
4
5. Polymorphism
Saifut
5
Class Ticket {
protected double weight; // allowed weight per bag
protected double nBags; // allowed number of bags
public virtual void AllowedBaggage() {
weight = 23;
nBags = 1;
}
Class Economy : Ticket {
:
// use default implementation
// of AllowedBaggage of base class
}
Class Business : Ticket {
:
Public override void AllowedBaggage() {
weight = 23;
nBags = 2;
}
Class First : Ticket {
:
Public override void AllowedBaggage() {
weight = 25;
nBags = 2;
}
6. Polymorphism
Saifut
6
Ticket t = null;
// create a Business, First or Economy ticket
// depending on which type of ticket was selected
// from the radio buttons on the form
if (rdoBusines.Checked )
t = new Business();
else if (rdoFirst.Checked)
t = new First();
else if (rdoEconomy.Checked)
t = new Economy();
// set the allowed baggage
// Note: C# will call the AllowedBaggage method of the class
// corresponding the object created. For example, if the object, t,
// was created as a First then First class’ method will be called
t.AllowedBaggage();
// print baggage information for the ticket
lstTicketInfo.Items.Add("Number of bags allowed: " + t.BAGS + “ Weight per bag: " + t.WEIGHT);