Java Polymorphism: Types And Examples (Geekster)

RahulAhuja837642 113 views 8 slides Dec 19, 2023
Slide 1
Slide 1 of 8
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8

About This Presentation

Polymorphism is one of the 4 pillars of Object-Oriented Programming. It is a
combination of two Greek words: poly and morphs. “Poly” means “many,” and
“morphs” means “forms.” So in Java, polymorphism means many forms.
Polymorphism is defined as the ability of a message to be displaye...


Slide Content

JAVAROADMAP
JavaPolymorphism–TypesAnd
Examples
Polymorphismisoneofthe4pillarsofObject-OrientedProgramming.Itisa
combinationoftwoGreekwords:polyandmorphs.“Poly”means“many,”and
“morphs”means“forms.”SoinJava,polymorphismmeansmanyforms.
Polymorphismisdefinedastheabilityofamessagetobedisplayedinmorethan
oneform.
Let’sunderstandthemeaningofpolymorphismbyanexample:
Considerawomaninsociety.Thesamewomanperformsdifferentrolesinsociety.
Thewomancanbethewifeofsomeone,themotherofherchild,canbeattherole
ofamanagerinanorganization,andmanymoreatthesametime.ButtheWoman
isonlyone.So,thesamewomanperformingdifferentrolesispolymorphism.
Anotherbestexampleisyoursmartphone.Thesmartphonecanactasaphone,
camera,musicplayer,alarm,andwhatnot,takingdifferentformsandhence
polymorphism

Introduction
PolymorphisminJavareferstoanobject’sabilitytotakeonmultipleformsortypes.
Itenablesthetreatmentofobjectsofdifferentclassesasobjectsofacommon
superclassorinterface.Insimplerterms,polymorphismallowsustorepresent
differenttypesofobjectsusingasinglevariableormethod.
Wecanrelatepolymorphisminreallifebythefollowingexample.Considerdifferent
typesofanimals.Eachanimalmakesadistinctsound.Byleveragingpolymorphism,
youcandefineacommon“makeSound”methodinasuperclasscalled“Animal,”
whichisoverriddenineachsubclasswiththespecificsoundimplementation.
//BaseclassAnimal
classAnimal{
publicvoidmakeSound(){
System.out.println("Animalmakingagenericsound...");
}
}
//SubclassDog
classDogextendsAnimal{
//OverridethemakeSoundmethodintheDogclass
publicvoidmakeSound(){
System.out.println("Dogbarking:Woof!");

}
}
//SubclassCat
classCatextendsAnimal{
//OverridethemakeSoundmethodintheCatclass
publicvoidmakeSound(){
System.out.println("Catmeowing:Meow!");
}
}
//SubclassCow
classCowextendsAnimal{
//OverridethemakeSoundmethodintheCowclass
publicvoidmakeSound(){
System.out.println("Cowmooing:Moo!");
}
}
publicclassMain{
publicstaticvoidmain(String[]args){
Animaldog=newDog();
Animalcat=newCat();
Animalcow=newCow();
dog.makeSound();
cat.makeSound();
cow.makeSound();
}
}
Output:
Dogbarking:Woof!
Catmeowing:Meow!
Cowmooing:Moo!
Inthisexample,wehaveabaseclassAnimalwithamakeSoundmethod.The
subclassesDog,Cat,andCowinheritfromtheAnimalclassandoverridethe
makeSoundmethodwiththeirspecificsound.Bycreatingobjectsofeachsubclass
andcallingthemakeSoundmethod,weobservepolymorphicbehaviorwhereeach
animalproducesitsuniquesound.
Thisexampledemonstrateshowpolymorphismallowsfortheflexibilityofhandling
differentobjectsthroughacommoninterfaceorsuperclass,enablingcodereuseand
promotingflexibilityinreal-lifescenarios.

Howpolymorphismcanbeachieved?
PolymorphisminJavacanbeachievedthroughtwoconceptsi.e.method
overloadingandmethodoverriding.Let’sdiveintoeachoftheseconcepts:
MethodOverloading
Polymorphismviamethodoverloadingenablesaclasstohavemultiplemethodswith
thesamenamebutdifferentparameters.Themethodscanperformsimilaractions
butwithdifferentdatatypesorparameters.TheJavacompilerdetermineswhich
methodtoinvokebasedonthemethodcallarguments.
Example:
classCalculator{
publicintadd(inta,intb){
returna+b;
}
publicdoubleadd(doublea,doubleb){
returna+b;
}
}
publicclassMain{
publicstaticvoidmain(String[]args){
Calculatorcalculator=newCalculator();
System.out.println(calculator.add(5,10));//Output:15
System.out.println(calculator.add(3.5,2.5));//Output:6.0
}
}
Intheexampleabove,theCalculatorclasshastwoadd()methods.Oneacceptstwo
integersasparameters,whiletheotheracceptstwodoubles.Dependingonthe
argumentspassedduringthemethodcall,thecompilerdeterminestheappropriate
methodtoinvoke.Thisallowsustousethesamemethodnameadd()fordifferent
datatypes,enhancingcodereadabilityandflexibility.
MethodOverriding
Polymorphismthroughmethodoverridingallowsasubclasstoprovideitsown
implementationofamethoddefinedinitsparentclass.Itinvolvescreatingamethod
inthesubclasswiththesamename,returntype,andparametersasthemethodin
theparentclass.Themethodinthesubclassoverridestheimplementationofthe
methodintheparentclass,allowingthesubclasstoexhibititsuniquebehavior.

Example:
classAnimal{
publicvoidmakeSound(){
System.out.println("Animalmakesasound");
}
}
classDogextendsAnimal{
@Override
publicvoidmakeSound(){
System.out.println("Dogbarks");
}
}
publicclassMain{
publicstaticvoidmain(String[]args){
Animalanimal=newDog();
animal.makeSound();//Output:Dogbarks
}
}
Intheexampleabove,wehaveasuperclasscalledAnimalwithamakeSound()
method.TheDogclassextendstheAnimalclassandoverridesthemakeSound()
methodwithitsownimplementation.WhenwecreateanobjectoftypeAnimaland
assignittoaDogobject,andthencallthemakeSound()method,itinvokesthe
overriddenmethodintheDogclass,displaying“Dogbarks”astheoutput.
TypesOfPolymorphismInJava
TherearetwotypesofpolymorphisminJava:compile-timepolymorphism(also
knownasmethodoverloading)andruntimepolymorphism(alsoknownasmethod
overriding).
1.Compile-TimePolymorphism(MethodOverloading)
ThistypeofpolymorphisminJavaisalsocalledstaticpolymorphismorstatic
methoddispatch.Itcanbeachievedbymethodoverloading.Inthisprocess,an
overloadedmethodisresolvedatcompiletimeratherthanresolvingatruntime.
●Methodoverloadingallowsaclasstohavemultiplemethodswiththesame
namebutdifferentparameters.

●Basedonthenumberandtypeoftheargumentspassedthecompiler
determineswhichmethodtocall.
●Themethodsmayhavedifferentreturntypes,butthisaloneisinsufficient
todistinguishoverloadedmethods.
Example1:MethodOverloadingwithDifferentNumberofParameters
publicclassCalculator{
publicintadd(inta,intb){
returna+b;
}
publicintadd(inta,intb,intc){
returna+b+c;
}
publicstaticvoidmain(String[]args){
Calculatorcalculator=newCalculator();
System.out.println(calculator.add(2,3));
System.out.println(calculator.add(2,3,4));
}
}
Output:
5
9
Inthisexample,theCalculatorclasshastwoaddmethods.Thefirstaddmethod
takestwoparameters,aandb,andreturnstheirsum.Thesecondaddmethodtakes
threeparameters,a,b,andc,andreturnstheirsum.Thetwomethodshavethe
samenamebutdifferentnumbersofparameters.Dependingonthenumberof
argumentspassedthecompilerselectstheappropriatemethod.
Example2:MethodOverloadingwithDifferentTypesofParameters
publicclassConverter{
publicStringconvertToString(intnumber){
returnString.valueOf(number);
}
publicStringconvertToString(doublenumber){
returnString.valueOf(number);
}

publicstaticvoidmain(String[]args){
Converterconverter=newConverter();
System.out.println(converter.convertToString(42));
System.out.println(converter.convertToString(3.14));
}
}
Output:
42
3.14
Inthisexample,theConverterclasshastwoconvertToStringmethods.Thefirst
convertToStringmethodtakesanintparameterandconvertsittoaString.The
secondconvertToStringmethodtakesadoubleparameterandconvertsittoaString.
Thetwomethodshavethesamenamebutdifferenttypesofparameters.Basedon
thetypeoftheargumentpassedthecompilerdetermineswhichmethodtoinvoke.
2.RuntimePolymorphism(MethodOverriding)
Dynamicmethoddispatchisanothernameforruntimepolymorphism.This
polymorphismisachievedbymethodoverriding.Theoverriddenmethodisresolved
atruntimeratherthanatcompiletime.
InJava,runtimepolymorphismoccurswhentwoormoreclassesarerelatedthrough
inheritance.Wemustcreatean“IS-A”relationshipbetweenclassesandoverridea
methodtoachieveruntimepolymorphism.
●Methodoverridingoccurswhenasubclassimplementsamethodthatis
alreadydefinedintheparentclass.
●Themustruleofmethodoverridingisthatthesubclassmethodmusthave
thesamename,returntype,andparameterlistastheparentclass
method.
●Themethodtoinvokeisdeterminedatruntimebasedontheactualtypeof
theobject.
●The@Overrideannotation(optionalbutrecommended)isfrequentlyused
toindicatethatamethodisintendedtooverrideasuperclassmethod.
Example1:MethodOverriding
classAnimal{
publicvoidmakeSound(){

System.out.println("Animalismakingasound");
}
}
classCatextendsAnimal{
@Override
publicvoidmakeSound(){
System.out.println("Catismeowing");
}
}
classDogextendsAnimal{
@Override
publicvoidmakeSound(){
System.out.println("Dogisbarking");
}
}
publicclassMain{
publicstaticvoidmain(String[]args){
Animalanimal1=newCat();
Animalanimal2=newDog();
animal1.makeSound();
animal2.makeSound();
}
}
Output:
Catismeowing
Dogisbarking
VISIT
BLOG.GEEKSTER.IN
FORTHEREMAINING
Tags