Java

Method Overriding In Java

Method overriding is the act of declaring a method in a subclass that is already existent in the parent class. A method that is already supplied by the parent class may be overridden to allow a child class to offer its own implementation. In this instance, the parent class method is referred to as the overridden method, and the child class method is referred to as the overriding method. The purpose of method overriding in Java will be discussed in this article.

Method Overriding Example

Let’s use a clear example to illustrate this. There are two courses here: a boy-child class and a human-parent class. Human class is expanded by Boy class. Each class shares the function void consume (). Boy class is overriding the eat() function by providing its own implementation, or doing so in other terms.

Here, the goal of Method Overriding is evident. In order to output Boy is eating instead of Human is eating when this method is called, the child class wishes to provide its own implementation.

class Human{
   //Overridden method
   public void eat()
   {
      System.out.println("Human is eating");
   }
}
class Boy extends Human{
   //Overriding method
   public void eat(){
      System.out.println("Boy is eating");
   }
   public static void main( String args[]) {
      Boy obj = new Boy();
      //This will call the child class version of eat()
      obj.eat();
   }
}

Output:

Boy is eating

Advantage of method overriding

The key benefit of method overriding is that it allows a class to customize an inherited method without ever altering the code of the parent class.

When a class contains numerous child classes, this is advantageous because it allows any child class that wants to utilize a parent class method to do so, while allowing other classes that wish to use a different implementation to do so by using the overriding feature without changing the parent class code.

Method Overriding and Dynamic Method Dispatch

Runtime polymorphism is shown through method overriding. Because the type of the object determines whether method (parent class or child class) is to be performed during method call, the call to the overridden method is decided at runtime when a parent class reference leads to a child class object. Dynamic method dispatch is the technique by which a call to an overridden method is handled at runtime. Here is an illustration to help you understand:

class ABC{
   //Overridden method
   public void disp()
   {
	System.out.println("disp() method of parent class");
   }	   
}
class Demo extends ABC{
   //Overriding method
   public void disp(){
	System.out.println("disp() method of Child class");
   }
   public void newMethod(){
	System.out.println("new method of child class");
   }
   public static void main( String args[]) {
	/* When Parent class reference refers to the parent class object
	 * then in this case overridden method (the method of parent class)
	 *  is called.
	 */
	ABC obj = new ABC();
	obj.disp();

	/* When parent class reference refers to the child class object
	 * then the overriding method (method of child class) is called.
	 * This is called dynamic method dispatch and runtime polymorphism
	 */
	ABC obj2 = new Demo();
	obj2.disp();
   }
}

Output:

disp() method of parent class
disp() method of Child class

Runtime polymorphism is used in the example above when the disp() function is called with a second object (obj2) (or dynamic method dispatch).
Note: In dynamic method dispatch, the object may call any non-overridden base class methods as well as any overridden child class methods, but it cannot call freshly specified child class methods. The object obj2 in the example above is calling the disp (). However, if you attempt to use obj2 to call the newMethod() function (which has just been defined in the Demo class), you will get the following compilation error message:

Exception in thread "main" java.lang.Error: Unresolved compilation 
problem: The method xyz() is undefined for the type ABC

Rules of method overriding in Java

1,Argument list: The child class method’s overriding method’s argument list must coincide with the overriding method’s argument list (the method of parent class). The arguments’ data types and order must be the exact same.

2, Access Modifier of the subclass method that is being overridden cannot be more restrictive than the access modifier of the parent class method. For instance, if the parent class method’s access modifier is public, the overriding method (child class method) cannot have the access modifiers private, protected, or default since each of these three access modifiers is more restricted than public.
For instance, this is prohibited because the child class’s disp method has additional limitations (protected) than the base class’s (public)

class MyBaseClass{
   public void disp()
   {
       System.out.println("Parent class method");
   }
}
class MyChildClass extends MyBaseClass{
   protected void disp(){
      System.out.println("Child class method");
   }
   public static void main( String args[]) {
      MyChildClass obj = new MyChildClass();
      obj.disp();
   }
}

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation 
problem: Cannot reduce the visibility of the inherited method from MyBaseClas

However, given that public is less limiting than protected, this eventuality is very plausible. Another acceptable modification is same access.

class MyBaseClass{
   protected void disp()
   {
       System.out.println("Parent class method");
   }
}
class MyChildClass extends MyBaseClass{
   public void disp(){
      System.out.println("Child class method");
   }
   public static void main( String args[]) {
      MyChildClass obj = new MyChildClass();
      obj.disp();
   }
}

Output:

Child class method

3,Since they are exclusive to the class, private, static, and final methods cannot be overridden. Although static methods may be re-declared in the subclass, the subclass method would behave differently and would not be related to the same static method of the parent class in this scenario.

4,No matter if the overridden method (method of parent class) throws any exceptions or not, the overriding method (method of child class) has the ability to throw unchecked exceptions. However, checked exceptions that are new or more inclusive than those stated by the overridden method should not be thrown by the overriding method. In the forthcoming lesson, we will go through this in great depth with examples.

4,Dynamic binding is the process of binding overridden methods during runtime.

6,A class must override all abstract methods if it extends an abstract class or implements an interface, unless the class is an abstract class in and of itself.

Super keyword in Method Overriding

For invoking the constructor or method of the parent class, use the super keyword. super. While super() calls the constructor of the base class, myMethod() calls the myMethod() method of the base class. Check out how super is used in method overriding.
Knowing that we have overridden a method in a child class, we may call the overridden method using an object from the child class. As seen in the example below, we may invoke the overridden method by using super:

class ABC{
   public void myMethod()
   {
	System.out.println("Overridden method");
   }	   
}
class Demo extends ABC{
   public void myMethod(){
	//This will call the myMethod() of parent class
	super.myMethod();
	System.out.println("Overriding method");
   }
   public static void main( String args[]) {
	Demo obj = new Demo();
	obj.myMethod();
   }
}

Output:

Class ABC: mymethod()
Class Test: mymethod()

 

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button