Chapter105:Polymorphism

No Comments

Section105.1:TypesofPolymorphism

Polymorphism means that a operation can also be applied to values of some other types. There are multiple types of Polymorphism:

  • Ad hoc polymorphism:

containsfunctionoverloading.ThetargetisthataMethodcanbeusedwithdifferenttypeswithoutthe needofbeinggeneric.

  • Parametric polymorphism:

istheuseofgenerictypes.SeeGenerics

  • Subtyping:

hasthetargetinheritofaclasstogeneralizeasimilarfunctionality

Adhocpolymorphism

ThetargetofAdhocpolymorphismistocreateamethod,thatcanbecalledbydifferentdatatypeswithoutaneed oftype-conversioninthefunctioncallorgenerics.Thefollowingmethod(s)sumInt(par1,par2)canbecalledwith differentdatatypesandhasforeachcombinationoftypesaownimplementation:

publicstaticintsumInt(inta,intb)

{

returna+b;

}

publicstaticintsumInt(stringa,stringb)

{

int_a,_b;

if(!Int32.TryParse(a,out_a))

_a=0;

if(!Int32.TryParse(b,out_b))

_b=0;

return_a+_b;

}

publicstaticintsumInt(stringa,intb)

{

int_a;

if(!Int32.TryParse(a,out_a))

_a=0;

return_a+b;

}

publicstaticintsumInt(inta,stringb)

{

returnsumInt(b,a);

}

publicstaticvoidMain()

{

Console.WriteLine(sumInt(1,2)); // 3
Console.WriteLine(sumInt(“3″,”4”)); // 7
Console.WriteLine(sumInt(“5”,6)); // 11
Console.WriteLine(sumInt(7,”8″)); // 15

}

Here’saexamplecall:

Subtyping

Subtypingistheuseofinheritfromabaseclasstogeneralizeasimilarbehavior:

publicinterfaceCar{

voidrefuel();

}

publicclassNormalCar:Car

{

publicvoidrefuel()

{

Console.WriteLine(“Refuelingwithpetrol”);

}

}

publicclassElectricCar:Car

{

publicvoidrefuel()

{

Console.WriteLine(“Chargingbattery”);

}

}

BothclassesNormalCarandElectricCarnowhaveamethodtorefuel,buttheirownimplementation.Here’sa Example:

publicstaticvoidMain()

{

List<Car>cars=newList<Car>(){

newNormalCar(),

newElectricCar()

};

cars.ForEach(x=>x.refuel());

}

Theoutput will be was following:

Refuelingwithpetrol Charging battery

Section105.2:AnotherPolymorphismExample

Polymorphism is one of the pillar of OOP. Poly derives from a Greek term which means ‘multiple forms’. Below is an example which exhibits Polymorphism. The class Vehicletakes multiple forms as a base class.

TheDerivedclassesDucatiandLamborghiniinheritsfromVehicleandoverridesthebaseclass’sDisplay()

method,todisplayitsownNumberOfWheels.

publicclassVehicle

{

protectedintNumberOfWheels{get;set;}=0;

publicVehicle()

{

}

publicvirtualvoidDisplay()

{

Console.WriteLine($”Thenumberofwheelsforthe{nameof(Vehicle)}is{NumberOfWheels}”);

}

}

publicclassDucati:Vehicle

{

publicDucati()

{

NoOfWheels=2;

}

publicoverridevoidDisplay()

{

Console.WriteLine($”Thenumberofwheelsforthe{nameof(Ducati)}is{NumberOfWheels}”);

}

}

publicclassLamborghini:Vehicle

{

publicLamborghini()

{

NoOfWheels=4;

}

publicoverridevoidDisplay()

{

Console.WriteLine($”Thenumberofwheelsforthe{nameof(Lamborghini)}is

{NumberOfWheels}”);

}

}

BelowisthecodesnippetwherePolymorphismisexhibited.TheobjectiscreatedforthebasetypeVehicleusinga variablevehicleatLine1.ItcallsthebaseclassmethodDisplay()atLine2anddisplaytheoutputasshown.

staticvoidMain(string[]args)

{

Vehiclevehicle=newVehicle(); //Line 1
vehicle.Display(); //Line 2
vehicle=newDucati(); //Line 3
vehicle.Display(); //Line 4
vehicle=newLamborghini(); //Line 5
vehicle.Display(); //Line 6

}

AtLine3,the vehicleobjectispointedtothederivedclassDucatiandcallsitsDisplay()method,whichdisplays theoutputasshown.Herecomesthepolymorphicbehavior,eventhoughtheobjectvehicleisoftypeVehicle,it callsthederivedclassmethodDisplay()asthetypeDucatioverridesthebaseclassDisplay()method,sincethe

vehicleobjectispointedtowardsDucati.

ThesameexplanationisapplicablewhenitinvokestheLamborghinitype’sDisplay()method. The Output is shown below

ThenumberofwheelsfortheVehicleis0 // Line 2

The number of wheels for the Ducati is 2 // Line 4

The number of wheels for the Lamborghini is 4 // Line 6

About us and this blog

We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

Request a free quote

We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

Subscribe to our newsletter!

More from our blog

See all posts
No Comments

Leave a Comment