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


When super class and the sub class contains same instance methods including parameters, when called, the super class method is overridden by the method of the sub class.

WIn this example super class and sub class have methods with same signature (method name and parameters) and when we try to invoke this method from the sub class the sub class method overrides the method in super class and gets executed.

Example

Live Demo

class Super{
   public void sample(){
      System.out.println("Method of the Super class");
   }
}
public class MethodOverriding extends Super {
   public void sample(){
      System.out.println("Method of the Sub class");
   }
   public static void main(String args[]){
      MethodOverriding obj = new MethodOverriding();
      obj.sample();
   }
}

Output

Method of the Sub class

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.

Example

Live Demo

class Super{
   public static void sample(){
      System.out.println("Method of the Super class");
   }
}
public class MethodHiding extends Super {
   public static void sample(){
      System.out.println("Method of the Sub class");
   }
   public static void main(String args[]){
      MethodHiding obj = new MethodHiding();
      obj.sample();
   }
}

Output

Method of the Sub class

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements