Tuesday, 12 December 2017

Object Oriented Programming(OOP) Explained with Java Examples (Part 5)

In this lesson, we are going to discuss the concept of polymorphism in the Java programming language.



What is Polymorphism
Polymorphism means the ability to exist in different forms. Remember that the three pillars of Object Oriented Programming is:
  • Inheritance
  • Abstraction
  • Polymorphism
We have already discussed Inheritance and Abstraction in previous lesson. So, to be able to follow this lesson, you need a knowledge of Inheritance but you can still follow

Step 1: Open Netbeans IDE and create an application

Step 2: Create a class and give it a name Animal

Step 3: Add a method to the class
Add a method to the class called MakeSound() defined  like this:

void MakeSound() {
    System.out.println("I can make a sound");


Step 4: Go to the function in the polymorphismLesson.java file, create a new Animal object and call its function, MakeNoise(). The two lines you need to type into your main program would be:

        Animal myPet = new Animal();   
        myPet.MakeSound();


Step 5: Run the program and observe that the programs runs and prints out:

I can make a sound

What happens is that the function MakeSound() of the Animal class is called.

Step 6: Now add three more classes to your program and name them:  Cat, Dog and Cow. Add function MakeSound() to each of them but with different implementations.

For the Cat class, the  implementation would be:
 System.out.println("I can make a sound, meew! meew!);

For the Dog:

System.out.println("I can make a sound, wow! wow!);

For the Cow:

System.out.println("I can make a sound, Moo! Moo!);

Step 7: Now go to the main program and create objects of these classes. Call the MakeNoise() method of each class and make sure it work


Polymorphism in Action
Lets now see how polymorphism works in all of these

Step 8: In your main function, create a cat object of the type Animal. Like this:

Animal myCat = new Cat(); 
myCat.MakeNoise();

Step 9: Run this program and observe that the MakeNoise() function of Cat is called

Step 10: Repeat the same for Dog and Cow and observe that the right function of each of them is called

The three objects myCat, myDog and myCow are of the same time Animal.  But when the MakeNoise() is called, the correct function is called based on the class it was created from. So we can say that the MakeNoise() function is a polymorphous function, that is same function but different behaves in different ways.

However, the concept of Polymorphism is not limited to just Polymorphous functions. In the next lesson, we would discuss another aspect of polymorphism and that is, Polymorphous Arrays.