60 likes | 76 Views
Polymorphism allows objects of different classes to be treated interchangeably, simplifying programming tasks. Learn why and how to apply polymorphism with examples in Java. Explore inheritance, abstract classes, and interfaces for flexible coding.
E N D
POLYMORPHISM • What is polymorphism ? • The feature that allows an object of a certain class to be seen also as an object of another • Why do we need it ? • Sometimes it makes programming easier • Example • We are dealing with different kinds of animals in a farm • We want to do the same things with them but they will react differently
Dealingwithanimals • Counthowmanylegswehave in total in a list of animals intlegs(Animal[] x) { //x isanarray of Animal objects intnlegs = 0; for(int i = 1; i < x.length; i++) if (x[i].name,equals(“Cat”)) nlegs += 4; elseif (x[i].name.equals(“Cock”)) nlegs+= 2; elseif (. . . • Whathappensifwehave a new type of animal ?
ApplyingPolymorphism • Letshaveeach animal defined as a differntclassbutall of themhave a methodcalledlegs() ClassCockextends Animal { . . . publicintlegs() { return 2; } . . . } intlegs(Animal[] x) { int n = 0; for(int i = 1; i < x.length; i++) n += x[i].legs(); return n; }
Resources in Java • In java we can haveanobject of class “Pig” and anobject of class “Cock” which can beealsoseen as of class “Animal” (thushavingthesamemthodsbutreactingdiffernt to it) by: • Simple inheritance: Animal declares nlegs(), Pig and Cockoverwriteit • Abstractclass: Animal declares nlegs() as abstract, Pig and Cockoverwriteit • No differencewith 1 whenwritingPig and Cock, • Preventusersfromcreating Animal objects • Interface: instead of writingclass Animal wewrite interface Animal which declares methodnlegs(), Pig and Cockimplementit
Letsseethe case of figures withall 3 • Wewillhave a base classGfigure • Fromthisonewewill “derive” Grectangle, Gcircle and Gtriangle • Theyhave a originpoint (x,y) and can be drawnover a Consoleobject • Consoleclasscreatedforthis lectura to easydrawings • Wewant to easilyresize and move figures ontheConsole • Folder figures simple inheritanceimplementsthiswith simple inheritance • Folder figures abstractclassesimplementsthiswithanabstractclass • Folder figures interface implementsthiswithan interface