Method Overriding in Java with Rules and Real-time Examples
Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java
Before we dive into the topic Method Overriding in Java extensively, let us look at a real-life example as always. Consider a family of three people, the father, the mother, and the son. The father decides to teach his son how to shoot. So he takes him to the range with his favorite rifle and trains him to aim at targets and shoot. However, the father is right-handed but the son is left-handed. So they have different methods of holding the gun! The father was worried that he might not be able to teach his son the art of shooting because of different orientations.
The son, however, was smart and decided to mimic the father’s hands by inverting them, i.e placing his dominant hand on the trigger rather than the father’s dominant hand. i.e the right hand. In this way, by slightly altering the method of learning, the son mastered the art of shooting!
This concept in programming is known as method overriding. Let us learn more about it.
Method Overriding in Java
The concept of method overriding is simply the redefining of the parent class method in the child class. The name of the method remains the same. However, the implementation of the same changes. Similar to the example above, the child class inherits all methods from the parent class father. However, the method shoot() gets redefined. That way the implementation of the method changes but the name still remains the same. This enables easier debugging and cleaner code.
If the subclass provides a specific definition of a parent class method, then this action is Method Overloading.
Advantages of Method Overriding in Java
The primary advantage of method overriding is that the child class can have a different implementation of a parent class method without even changing the definition of the parent class method.
How is this useful?
For example, if a parent class has multiple child classes, each child class can have its own implementation of the parent class method.
However, when a parent class reference points to a child class object, the compiler resolves the object call during runtime. This is a dynamic method dispatch.
Program to illustrate Java Method Overriding:
package com.dataflair.javamethodoverriding; class Father { void shoot() { System.out.println("I am the father! I am a right-handed shooter! "); } } public class Child extends Father { void shoot() { System.out.println("I am the son! I am a left-handed shooter!"); } public static void main(String[] args) { Father f = new Father(); f.shoot(); //Here the parent class method gets called. Father fc = new Child(); fc.shoot(); //This is dynamic methpod dispatch. The compiler decides method call at runtime. } }
Output:
I am the son! I am a left-handed shooter!
Note that the dynamic method dispatch executes the child class method.
In Java you can also override methods while using multiple inheritances. The method in the parent class can be overridden in all of its successive child classes.
Program to illustrate the use of method overriding in multilevel inheritance in Java:
package com.dataflair.javamethodoverriding; class GrandFather { void move() { System.out.println("I use my stick to move!"); } } class Father extends GrandFather { void move() { System.out.println("I can walk fast!"); } } class Baby extends Father { void move() { System.out.println("I crawl and have fun!"); } public static void main(String[] args) { GrandFather ob = new Baby(); ob.move(); } }
Output:
When should you use Java method overriding?
Learning about the intricacies of method overriding and its actual implementation are crucial to developing good software. This prevents code redundancy and results in easy debugging because of good structure.
You should use method overriding when there is a need to implement a specific functionality of a child class which is unique to the class itself. But you might think that “Why not put it in a separate function altogether?” Well you are not the first one to think like that. But, the same method can have different implementations in different classes too!
Note the example above. You may realize that we could easily have made a different method for the class Child named “shoot child()” and written class-specific code there! But what we managed to do was keep the same name of the function as the parent class itself! That way when you try to debug the code and you realize that there is an error in the shoot() function, you can straightaway go to the class Child and debug your code inside the function. Having different names is tedious and difficult to maintain.
Method Overriding in Inheritance Hierarchies
Method overriding becomes even more interesting in scenarios with multiple inheritance levels. Consider a class hierarchy where Child inherits from Parent, and GrandChild inherits from Child. In this case:
- GrandChild can override methods inherited from both Parent and Child.
- The overriding method in GrandChild will be invoked at runtime if a GrandChild object is referenced by a Parent class variable.
This cascaded overriding mechanism provides flexibility in inheritance hierarchies, allowing for specialized behavior in descendant classes.
Usage of Method Overriding in Java
The overriding has the following uses in java:
- It provides a specific implementation of a predefined method.
- Implements runtime polymorphism.
Rules to follow while implementing Java Method Overriding
There are a few rules when it comes to implementing Method Overriding:
a. The method should have the same name as the parent class method which is overriding.
b. All the parameters/arguments of the method should match. Remember, this is no method overloading. These two are completely different concepts. For example, if the parent class method has two integer arguments, then the child class method should also accept two integer arguments.
c. The overriding method access specifier cannot be more restrictive than the parent class access specifier. For example, if the parent method is public then the child class cannot be default or private or protected because all of these access specifiers are more restrictive in nature than the public. We will explain this later in this article.
d. static, final, and private access restrict the method from overriding. This means that any parent class method which has a private access specifier or is static or final in nature cannot be overridden by any of its child classes.
e. We also cannot override the main method in Java.
f. If the class is implementing another class which is abstract or implementing an interface, then the class has to override all of the functions, unless the class is an abstract class in itself.
g. The overriding method may have unchecked exceptions because the implementation is different from the method in the parent class. However, there should be no additional checked exceptions other than the exceptions in the parent class method.
h. The class should follow an “IS-A” relationship, i.e, the classes should be implementing inheritance.
Okay enough of the theory! Let us dive into some code!
Method overriding with Access Specifiers in Java
package com.dataflair.javamethodoverriding; class Father { // private methods are not overridden private void method1() { System.out.println("From Father method1()"); } protected void method2() { System.out.println("From Father method2()"); } } class Child extends Father { // new method1() method // This method is unique to Child class private void method1() { System.out.println("From Child method1()"); } // overriding method // with greater accessibility public void method2() { System.out.println("From Child method2()"); } } // Driver class class Main { public static void main(String[] args) { Father obj1 = new Father(); obj1.method2(); Father obj2 = new Child(); obj2.method2(); } }
Output:
From Child method2()
The private method in the above example is not printed because it is non-overridable.
Static methods in Java are non-overridable
If you override a static method in the parent class with the static method in the child class then the method in the parent class hides the child class method. Let us see an example. However if you try to override a static method from a non-static method context, or vice versa, the compiler returns an error.
Java program to illustrate static method overriding:
package com.dataflair.javamethodoverriding; class Father { // private methods are not overridden static void method1() { System.out.println("From static Father method1()"); } void method2() { System.out.println("From Father method2()"); } } class Child extends Father { // new method1() method // This method is unique to Child class static void method1() { System.out.println("From static Child method1()"); } // overriding method // with greater accessibility void method2() { System.out.println("From Child method2()"); } } // Driver class class StaticOverride { public static void main(String[] args) { Father obj1 = new Father(); obj1.method2(); Father obj2 = new Child(); obj2.method1(); //According to dynamic method dispatch this should execute child class method but this executes parent class method. } }
Output:
From static Father method1()
You cannot override final methods in java
If you have a method declared as final in your parent class then that method is non-overridable. Let us see for ourselves.
Program to illustrate Java final method:
package com.dataflair.javamethodoverriding; class Father { final void shoot() { System.out.println("I am the father! I am a right handed shooter! "); } } public class Child extends Father { void shoot() { super.shoot(); System.out.println("I am the son! I am a left handed shooter!"); } public static void main(String[] args) { Father fc = new Child(); fc.shoot(); //This is the method which houses the super keyword for calling the parent class method. } }
Output:
void shoot()
^
overridden method is final
1 error
Exception Handling and Method Overriding in Java
There are certain rules when it comes to using exception handling and method overriding. One of them is that if the superclass method does not throw any checked exceptions, then the subclass method can only throw unchecked exceptions. If it tries to throw checked exceptions then the compiler returns an error.
Let us see with an example:
package com.dataflair.javamethodoverriding; class Parent { void methodname() { System.out.println("I do not have any checked excpetions."); } } class Child extends Parent { void methodname() throws IOException { System.out.println("I throw checked exceptions"); } } public class MainException { public static void main(String[] args) { Parent p = new Child(); p.methodname(); } }
Output:
void methodname()throws IOException
^
overridden method does not throw IOException
2 errors
Points to Remember while using method overriding in Java
If the parent class method throws a checked exception, then the child class method may or may not throw an exception at all. But if it does throw an exception it must be the same exception or its subclass. However if the parent exception is Exception Hierarchy then a compile error occurs. Let us understand with an example:
package com.dataflair.javamethodoverriding; import java.io. * ; class Parent { void methodname() throws IOException { System.out.println("I do not have any checked excpetions."); } } class Child1 extends Parent { void methodname() throws IOException { System.out.println("I throw checked exceptions"); } } class Child2 extends Parent { void methodname() throws Exception { System.out.println("Exception Hierarchy"); } } public class MainException { public static void main(String[] args) { Parent p = new Child1(); p.methodname(); Parent p1 = new Child2(); p1.methodname(); } }
Output:
void methodname()throws Exception{
^
overridden method does not throw Exception
1 error
Super Keyword in Java
The super keyword is essential as it calls the parent constructor or a parent class method in the child class. In order to call the parent class constructor, we use super() and for calling a superclass method named as supermethod(), the syntax is super.supermethod(); Let us take a look at one example:
Java program to illustrate the use of super keyword:
package com.dataflair.javamethodoverriding; class Father { void shoot() { System.out.println("I am the father! I am a right-handed shooter! "); } } public class Child extends Father { void shoot() { super.shoot(); //This super keyword calls the method with the same name in the parent class. System.out.println("I am the son! I am a left-handed shooter!"); } public static void main(String[] args) { Father fc = new Child(); fc.shoot(); //This is the method which houses the super keyword for calling the parent class method. } }
Output:
I am the son! I am a left-handed shooter!
Summary
Finally, In this article, we learned about the various types of method overriding and its uses in java. Method overriding implements polymorphism in the language which is essential to master. We also learned about the super keyword and the rules of method overriding.
Your opinion matters
Please write your valuable feedback about DataFlair on Google
Hey,it was a great article.I found it very useful for me please keep posting such articles.I would love to learn form your article. Thanks.
Hi Kiran,
We are glad our loyal reader like our Java tutorial for method overriding. Our team continuously works to provide important and relevant information for the reader.
Please share and suggest this blog with your peer groups.
Regards,
DataFlair