Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Method Hiding In Java?
2.1.
Java
3.
Methods in Static Context
4.
What is Method Hiding?
5.
Features of Method Hiding in Java
6.
Method Hiding Factors (MHF)
7.
Examples of Method Hiding in Java
7.1.
Example 1:
7.2.
Java
7.3.
Example 2:
7.4.
Java
7.5.
Example 3:
7.6.
Java
8.
Method Overriding Vs Method Hiding
8.1.
Let's understand the method of handing and overriding practically.
8.2.
Define a method with the same signature as in superclass.
9.
Frequently Asked Questions
9.1.
What is the benefit of Method hiding in Java?
9.2.
Why is it called Method hiding in Java?
9.3.
Why is the method hiding compile time polymorphism?
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

Method Hiding in Java

Author yuvatimankar
0 upvote

Introduction

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 is connected to Method overriding, and a coder may hide a method while attempting to override it.

method hiding in java

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();

animal.makeSound();
cat.makeSound();
dog.makeSound();
}
}

Output:-

Animals make sounds
Cat meows
Dog barks

 

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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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(); 

Output:

Output


You can also find the output of this java compiler code here.

Example 2:

  • Java

Java

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();
  }
}

Output:

Output


Example 3:

  • Java

Java

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();  
       }
   }

Output:

Output

You can also read about Java DestructorDuck Number in Java

Method Overriding Vs Method Hiding

Method Overriding

Method Hiding

Both methods created in a program must be non-static. Both methods created in a program must be static.
It is considered dynamic polymorphism or runtime polymorphism or late binding. It is considered static polymorphism or compile-time polymorphism or early binding.
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.

Conclusion

In this article, we have discussed the Method hiding in Java. It presents a powerful mechanism for refining and customizing the behavior 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.

To read more on OOPs concepts, you can see our blog OOPS in Javamethod overloadingException handling with Method overriding in JavaPolymorphismoverloading, and overriding static methods in Java. You can also see our java course here.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive ProgrammingJavaScriptSystem Design, etc. Enroll in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Happy learning, Ninja🥷

Live masterclass