Polymorphism in Java
What is P0lymorphism in Java >
Simple Explanation– A Single Method in a parent class , can be use different way by its child Class through referencing.
Class Animalss
- First i have created a parent class i called it “animalss”
- All animals make noise right
- The next step i have created a method call ” makeNoise()”
package polys; public class acessAnimals { public static void main(String[] args) { animalss referrals; referrals = new knine(); referrals.makeNoise(); referrals = new kittys(); referrals.makeNoise(); } }
Class knine
- Then I created a Child Class called knine
- I created a method name makeNoise() same as the Parent / Super Class animalss
- Then i modify the Out put of the Method makeNoise()
- Dog Make noise “Woof Woof “
- I repeat the step above from 1 to 4 and create a child class call Kittys
package polys; public class knine extends animalss { public void makeNoise(){ System.out.println("Woof woof"); } }
Class kittys
package polys; public class kittys extends animalss { public void makeNoise(){ System.out.println("Miao Miao"); } }
Class accessanimals
- I create this class to acces the kninne and kittys class
- I declare a referencings called “referrals” towards the animalss parent object
- The ” referrals ” is refer to the new object knine
- Print out the Knine method “makeNoise “
- The ” referrals ” is refer to the new object kittys
- Print out the kittys method “makeNoise “
package polys; public class acessAnimals { public static void main(String[] args) { animalss referrals; referrals = new knine(); referrals.makeNoise(); referrals = new kittys(); referrals.makeNoise(); } }
Output
Check out Map in Java here
Leave a Reply