Day6 of #100DaysOfCode Challenge: Polymorphism in Java By Example

According to dictionary provide by Google(R), polymorphism is the occurrence of different forms among the members of a population or colony, or in the life cycle of an individual organism. In java programming according to Oracle(R) docs, a Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.

To demonstrate how Polymorphism in Java is, let’s take a look this example and see how.
1. We created the Person class with a method getAge() that return ‘0’ for the age of the person and a method canWalk() to determine if the person can walk.
2. Then we created the Student class that extends Person class.
3. In the Student class, we added the exact the same method signature getAge() and optionally added the @Override annotation.
4. We also added the isStillGoingToSchool() method to the Student class.


The age of the person is 10
It is false that this Person can walk

What happen when we execute our code?
After instantiating the Student class as Person we called the persons.getAge() method. During this execution, java determines the which method to be called, because we use Student that extends the Person, java will take the reference of the method from the Student class. Next is, we execute the method person.canWalk(), and because Student class doesn’t have method canWalk(), java then executes the Person’s canWalk() method.

On the second part of the code we instantiate the Student and this time as Student and the difference of this against the previous execution, the method isStillGoingToSchool() is excutable.

Example error when we try to call person.isStillGoingToSchool() even though the it’s a Student instance


if you want to contribute and improve this post, just comment below.

Leave a Reply

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