In the previous article, we covered class inheritance in Java, which is a feature to copy methods and member variables of another class into our class. We gave an example that since a square is a rectangle, the
Square class can inherit the
Rectangle class and get the
area() for free.
But what happens when we inherit too much? The parent class we are inheriting from has a method that does not do what we want. In this case, we can override the behavior of such methods in our class. All we have to do to override a method is just provide our own definition of the method. Let’s see how overriding works.
Override a Method
The following program shows an example of method overriding. Class
Child inherits class
Parent, and overrides method
Output: Hi this is the child! Hi this is the parent!
Clearly, when overriding a method, the methods must have matching name and the parameter list.
Notice that although the child class overrides
greet(), the parent’s version is still accessible through the
Methods with the
static modifier cannot be overriden. When a method with the same signature is present in the child class, it may appear that the method is overriden, but this is called method hiding.
Overriding and hiding are similar concepts. The difference is in scenarios of polymorphism. The following example shows the difference.
Output: Instance method of Child Static method of Parent
Finally, non-static methods marked with
final modifier cannot be overriden. When attempted, compiling error will occur.