Method Hiding in Java
In this section, we will discuss what is method hiding in Java, method hiding factors (MHF), and the differences between method hiding and method overriding. Also, implement the method hiding concept in a Java program.
To understand the method hiding concept in Java, first, we will understand the method overriding. Because the method hiding concept is very similar to the method overriding.
What is method overriding?
Method overriding means subclass had defined an instance method with the same signature and return type as the instance method in the superclass. In such a case, method of the superclass is overridden (replaced) by the subclass.
Methods in Static Context
Static methods are bonded during compile time using types of reference variables not object. We know that static methods are accessed by using the class name rather than an object. Note that the static method can be overloaded, but cannot be overridden in Java.
What is method hiding?
Method hiding can be defined as, "if a subclass defines a static method with the same signature as a static method in the super class, in such a case, the method in the subclass hides the one in the superclass." The mechanism is known as method hiding. It happens because static methods are resolved at compile time.
Method Hiding Factors (MHF)
Example of Method Hiding in Java
Method-1 of the Demo class is executed. Method-1 of the Demo class is executed. Method-2 of the Demo class is executed. Method-2 of the Sample class is executed.
We observe that the method of the superclass is hidden by the subclass.
Method Hiding Vs. Method Overriding
Hiding a static method of a superclass looks like overriding an instance method of a superclass. The main difference can be seen at runtime in the following scenario.
Let's understand the method handing and overriding practically.
The above code snippet does not perform the method hiding because the methods of both the classes are non-static, hence they perform method overriding.
In the above code snippet, to achieve the method hiding, we need to make the methods static.
The following table describes what happens when we define a method with the same signature as in superclass.
Note: In a subclass, we can overload the methods inherited from the superclass. The overloaded methods neither hide nor override the superclass instance methods. These are the new methods, that are unique to the subclass.