Java is an object-oriented programming language which strictly adheres to core principles of object-oriented programming – Encapsulation, Inheritance and Polymorphism.
Overriding implies writing your own version on top of a default implementation of a method in the parent class. Let us say we have a class ‘Person which’ is extended by class ‘Teacher’ and by class ‘Homemaker‘. The person class has a method ‘pickFurniture()’ which allows the person in context say Homemaker or Teacher to implement own version of the method by overriding according to his/her choice.
The screenshot below is Enum definition which contains all possible furniture available for selection by the ‘pickFurniture’ method.

The ‘pickfurniture‘ method shown below is the default implementation. Note that I have added two elements from the FurnitureEnum to the arraylist ‘listOfFurniture‘. Person class is parent to Teacher and HomeMaker. In this case the Teacher will pick a furniture list of his or her choice instead of the default furniture list picked by the ‘Person‘ class and the ‘HomeMaker’ will extend the Person class using ‘extends’ keyword to override ‘pickFurniture’ method to pick the furniture of his/her choice.
This means when you call the ‘pickFurniture’ method in your program the furniture list that is returned by the method depends on the type of person and ‘pickFurniture’ implementation in the child class.


Note – Without the ‘extends’ keyword the parent class attributes / properties and methods will not be inherited to the child class to override.

The Tricky Situation :
Consider this piece of code and try and print the output. Compare the results with your manual computation. If results match then you have it right when it comes to overriding.
Scenario 1:
What will be the result of calling the 'pickFurniture' on each of the person instance shown below?
Person p1 = new Person();
Person p2 = new Teacher();
Person p3 = new Homemaker();
Output:

Clearly the JVM looks at the instance type and not the reference type when it comes to overriding. This is very important to understand otherwise we are missing out on how overriding works.
Try guessing the results of similar code snippet below to verify your understanding.
Scenario 2:
What will be the result of calling the 'pickFurniture' method here?
Person p1 = new Person();
Person p2 = new Person();
Person p3 = new Person();
Scenario 3:
What will be the result of calling the 'pickFurniture' method here?Person p1 = new Person();
Teacher t1 = new Teacher();
Homemaker h1 = new Homemaker();
Thanks for reading !! Watch out more blog posts on Java fundamentals !!!
Leave a Reply