Java Method Overriding

In any object-oriented programming language, Method Overriding is a feature that allows the user to declare a method with the same name in a sub-class that is already present in a parent-class. That is when a sub-class inherits from its super-class and both have the same-named method than by overriding features, different tasks can be applied to both of the methods.

Method overriding is used for runtime Polymorphism.

Example of method overriding in Java:

Output method overriding:

Explanation:
In the above example, we can see that ‘b‘ is a type of dog but still executes the display method in the breed class. In the runtime, JVM first looks at the object type and run the method that belongs to that particular object.

Since the class Dog has the method display, the compiler will have no problem in compiling, and during runtime, the method specific for that particular object will run.

But look at the below example:

Output:

Here it shows error for the method doSleep() because the object created is of type Dog that does not have the dogSleep() method and is not Overriden in the breed class.


Rules for Overriding a Method:

  • The Overriden and Overriding methods must have the same name and the same argument list.
  • Method Overriding requires Inheritance of a class otherwise the method cannot be overridden.
  • Restriction to use Access-modifier, that is if a, access-modifier of the method is declared public in a parent class then it cannot be an overriding method of a sub-class or child-class cannot have protected, private and default access-modifier.
  • private, static and final methods cannot be overridden as they are local to the class. But the static method can be re-declared.
  • A child class within the same package as the instance’s parent class can override any parent class method that is not declared private or final.
  • Constructors cannot be overridden.
  • Overriding method (that is the method present in the sub-class) can throw unchecked exceptions, whether the Overriden method (that is the method present in the parent-class) throws an exception or not.

Use of Super keyword in Method Overriding:

The super keyword in Java is used in the sub-class for calling the inherited parent class method/constructor. When we execute super.myMethodName in sub-class inside the method, it invokes the method of parent-class having method name ‘myMethodName’.

Example of Super keyword in Method Overriding:

Output:

In this example, we create the Object for Breed class. And ‘super.display()’ calls the ‘display()‘ method from the Dog class that is the parent class. and hence we get ‘I am a Dog‘ result too.
But if we eliminate ‘super.display()‘ then we only get the result as ‘Breed: German Shepard‘.


Method.
Method Overloading.
Static and dynamic binding.