Do you think IIT Guwahati certified course can help you in your career?
No
In Java, we must be careful about the possibility of method hiding. A method in a subclass with the same signature and type as a method in a superclass can hide variables in the superclass. Method hiding in Java is connected to Method overriding, and a coder may hide a method while attempting to override it.
In this blog, we will see what Method hiding in Java is and its features, how MHF(method hiding factors) works, and the difference between Method overriding and Method hiding.
Let's start and stay till the end!
What is Method Hiding In Java?
Method hiding in Java is functionally very same as Method overriding. Method hiding in Java can occur in any hierarchy structure. Overriding allows calling methods referenced on the instance type if we construct a method in a subclass with the same signature and type. When static methods in both the superclass and a subclass have the same signature and type, the subclass Method hides the Method in the superclass.
In other words, Method hiding in Java is defined as “if a subclass defines a static method with a similar signature as a static method in the superclass, in that case, the Method in the subclass hides the one present in the superclass”.
This feature allows an instance method defined in the base class to be replaced by an implementation of that method in the child class. The return type, name, and parameters should be the same, or in other words, the signatures should match.
The following code in Java illustrates method overriding:-
Java
Java
class Animal { public void makeSound() { System.out.println("Animals make sounds"); } } class Cat extends Animal { @Override public void makeSound() {//makeSound() implementation of cat class System.out.println("Cat meows"); } } class Dog extends Animal { @Override public void makeSound() {//makeSound() implementation of dog class System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Animal animal = new Animal(); Cat cat = new Cat(); Dog dog = new Dog();
In the above example makeSound() instance method of the Cat and Dog class override the makeSound() method in the Animal class, however, it can still be accessed from its own object.
Methods in Static Context
Static methods cannot be overridden in Java, they are associated with the class rather than instances or objects of that class. You can declare static methods in Java using the ‘static’ keyword before the method signature.
What is Method Hiding?
Method hiding is a mechanism in Java that occurs when a child class provides its own implementation of a static method, the method in the parent class is completely hidden as method hiding is resolved in compile time. This method is not applicable to instance methods.
Features of Method Hiding in Java
Here are some key features of method hiding in Java:
Static Methods: Method hiding only applies to static methods, not to instance methods. Static methods are associated with the class itself rather than with any instance of the class.
Inheritance: Method hiding is a feature of inheritance in Java. It allows a subclass to provide a specific implementation of a static method without overriding the method of the superclass.
Same Signature: The static method in the subclass must have the same method signature (name and parameters) as the static method in the superclass that it intends to hide.
No Polymorphism: Method hiding does not exhibit polymorphic behavior because it is resolved at compile time based on the reference type, not the actual object type.
Compile-Time Binding: Method hiding involves compile-time binding, where the compiler determines which method to call based on the reference type rather than the actual object type.
Method Hiding Factors (MHF)
Below are some method hiding factors:
The method hiding factors are used to measure the invisibilities of methods in classes.
The percentage of classes in total from which a method is invisible is referred to as its invisibility.
An attribute is said to be visible if another object or class can retrieve it. An attribute should be hidden within a class, and we can use the keyword "private" if we want to keep it from being retrieved by other objects.
The number of visible methods present shows the class functionality. Method Hiding Factor is reduced by increasing the overall functionality.
A low MHF indicates that the execution was not correctly abstracted. Most methods are unprotected, so the risk of error is high.
A high MHF indicates a lack of functionality. It can also indicate that the design contains a significant amount/portion of specialized methods which are not reusable.
The Method hiding factor should ideally have a high value.
The formula for computing the MHF is :
The sum of the invisibilities of all methods defined in all classes / Total number of methods defined in the project.
Examples of Method Hiding in Java
Example 1:
Java
Java
class Ninja { public static void method1() { System.out.println("Method-1 of the Ninja class is executed."); } public void method2() { System.out.println("Method-2 of the Ninja class is executed."); } }
/* child class */ class Sample extends Ninja { public static void method1() { System.out.println("Method-1 of the Sample class is executed."); } public void method2() { System.out.println("Method-2 of the Sample class is executed."); }
public static void main(String args[]) { Ninja d1 = new Ninja();
/*d2 is the reference variable of class Ninja that points to the object of class Sample */ Ninja d2 = new Sample();
/* method calling with reference (method hiding) */ d1.method1(); d2.method1();
/* method calling with an object (method overriding) */ d1.method2(); d2.method2(); } }
You can also try this code with Online Java Compiler
Method-1 of the Ninja class is executed. Method-1 of the Ninja class is executed.
Method-2 of the Ninja class is executed.
Method-2 of the Sample class is executed.
class Super{ public static void sample(){ System.out.println("Method of the Superclass"); } } class MethHiding extends Super { public static void sample(){ System.out.println("Method of the Subclass"); } public static void main(String args[]){ MethHiding obj = new MethHiding(); obj.sample(); } }
You can also try this code with Online Java Compiler
class Parent { public static void sleep() { System.out.println("Parent sleeps at 9 PM"); } } class Child extends Parent { public static void sleep() { System.out.println("Child sleeps at 11 PM"); } } class Code { public static void main(String[] args) { Parent p = new Parent(); Parent c = new Child(); p.sleep(); c.sleep(); } }
You can also try this code with Online Java Compiler
Difference Between Method Overriding and Method Hiding
Parameters
Method Overriding
Method Hiding
Static/Non-static
Both methods created in a program must be non-static.
Both methods created in a program must be static.
Other Name
It is considered dynamic polymorphism or runtime polymorphism or late binding.
It is considered static polymorphism or compile-time polymorphism or early binding.
Handled by
JVM handles method resolution based on runtime objects.
The compiler handles method resolution based on the reference type.
Let's understand the method of handing and overriding practically.
Method overriding is a concept in object-oriented programming where a subclass provides a specific implementation for a method already defined in its superclass. When the subclass has a method with the same name, return type, and parameters as the one in its superclass, the subclass's method will override the superclass's method. To understand method overriding practically, consider the following analogy: A company with a hierarchical structure. The company has a general policy for how employees should handle customer inquiries. This policy is defined in the Employee Handbook (the superclass). Different departments within the company have their specific way of handling customer inquiries. For example, the Sales department might have another script to follow compared to the Support department. Each department (subclass) can override the default policy from the Employee Handbook with its specific procedures.
Define a method with the same signature as in superclass.
Suppose we have a superclass called Shape, which has a method called calculateArea():
Superclass (Shape)
Subclass (Rectangle)
Method: calculateArea()
Method: calculateArea()
Signature: calculateArea()
Signature: calculateArea()
Return Type: double
Return Type: double
Parameters: None
Parameters: None
Now, let us create a subclass called Rectangle, which extends the Shape class and also has a method called calculateArea(), but with the same signature as in the superclass: Explanation: Both the superclass (Shape) and subclass (Rectangle) have a method called calculateArea() with the same signature, which means they have the same method name, return type (double), and no parameters. This demonstrates method overriding, where the subclass provides a specific implementation for the method already defined in the superclass. When an object of the Rectangle class calls the calculateArea() method, the overridden method in the Rectangle class will be executed instead of the one in the Shape class. Recommended Topic: Solid Principles in java
Frequently Asked Questions
What is the benefit of Method hiding in Java?
Method hiding exhibits static polymorphism in Java. It also makes your code more extensible as the base classes can extend the functionality of super classes.
Why is it called Method hiding in Java?
It is known as Method hiding in Java because the Method in the superclass will be hidden by the Method present in the subclass.
Why is the method hiding compile time polymorphism?
It is known as compile-time polymorphism because the compiler is accountable for solving method resolution based on the reference type.
Why do we do method hiding?
Method hiding in object-oriented programming is done to redefine a static method in a subclass that already exists in a superclass. This allows the subclass to provide its own version of the method without affecting the superclass's implementation.
How abstraction is different from method hiding?
Abstraction focuses on hiding implementation details and exposing only essential features to the user, typically through interfaces or abstract classes. It promotes cleaner, modular code. Method hiding, on the other hand, involves redefining a static method in a subclass to "hide" the superclass's method, but it doesn't impact the abstraction of behavior.
Conclusion
In this article, we have discussed the Method hiding in Java. It presents a powerful mechanism for refining and customizing the behaviour of static methods within class hierarchies. By allowing subclasses to define static methods with the same signature as those in their superclasses, method hiding enables developers to provide specialized implementations while maintaining the structure and integrity of their codebase.