Polymorphism in Java

Polymorphism in Java

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

  1. First i have created a parent class i called it “animalss”
  2. All animals make noise right
  3. 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

  1. Then I created a Child Class called knine
  2. I created a method name makeNoise() same as the Parent / Super Class animalss
  3. Then i modify the Out put of the Method makeNoise()
  4. Dog Make noise “Woof Woof “
  5. 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

 

  1. I create this class to acces the kninne and kittys class
  2. I declare a referencings called “referrals” towards the animalss parent object
  3. The ” referrals ” is refer to the new object knine
  4. Print out the Knine method “makeNoise “
  5. The ” referrals ” is refer to the new object kittys
  6. 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

Your email address will not be published. Required fields are marked *

5 × 5 =