What is the difference between method overloading and method hiding in Java?


method hiding − When super class and the sub class contains same methods including parameters, and if they are static and, when called, the super class method is hidden by the method of the sub class this is known as method hiding.

Example

Live Demo

class Demo{
   public static void demoMethod() {
      System.out.println("method of super class");
   }
}
public class Sample extends Demo{
   public static void demoMethod() {
      System.out.println("method of sub class");
   }
   public static void main(String args[] ){
      Sample.demoMethod();
   }
}

Output

method of sub class

method overloading − When a class contains two methods with same name and different parameters, when called, JVM executes this method based on the method parameters this is known as method overloading.

Example

Live Demo

public class Sample{
   public static void add(int a, int b){
      System.out.println(a+b);
   }
   public static void add(int a, int b, int c){
      System.out.println(a+b+c);
   }
   public static void main(String args[]){
      Sample obj = new Sample();
      obj.add(20, 40);
      obj.add(40, 50, 60);
   }
}

Output

60 
150

Updated on: 30-Jul-2019

695 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements