Method overriding in Java

Here is the table content of the article will we will cover this topic.
1. What is Method overriding in Java?
2. What are the Rules of
Method overriding in Java?
3. Method overriding in Exception handling?
4. Can we override the final method in java?
5. Can we override the static method in java?
6. Difference between overloading and overriding?

What is Method overriding in Java?

In this article we will discuss the method overriding in Java. To overload a method, we will read the different rules. You should read about the inheritance first if you have not read the inheritance yet. Because you should have basic knowledge of inheritance.

Method overriding in java is only possible with the concept of Inheritance. As you know by use of inheritance concept in Java, we can inherit the method of the parent class to child class. Method overriding in Java is a feature through which we can define the method in child class that is already defined in parent classes. If a method in a child class has the same name, and parameters as a method defined in parent class, then the method is defined in the subclass is called overridding method and the method defined in the parent class is called an overridden method.

Whenever a child class extends a parent class, the child class automatically inherits all the methods defined in the parent class(Obviously private method doesn’t inherit). These methods are known as derived methods.
Java allows providing a specific implementation of a method in child class.

method overriding in java

Let’s say a parent class has a method sum(int, int) and a child class provides the specific implementation of the method (sum(int, int)) that has been declared in the parent class. It is known as method overriding.

class ParentClass
{
   // Overridden method
   public void printData()
   {
      System.out.println("In this method we are showing the details of Parent class");
   }
}
class ChildClass extends ParentClass
{
  	 //Overriding method
	public void printData()
	{
	     System.out.println("In this method we are showing the details of child class");
	     System.out.println("We are overriding the method");
	}
   public static void main( String args[]) {
	   ParentClass parentObject = new ChildClass();
      //This will call the child class method
	   parentObject.printData();
   }
}

Output:
In this method we are showing the details of child class
We are overriding the method
Advantage of method overriding:

What are the rules to Method overriding in Java?

We will use two terms here one is overridding method and overridden method. The method is defined in the subclass is called overridding method and method defined in the parent class is called an overridden method.

1. Argument/Parameters list

While overriding the method in child class we should take care of method name, the number of parameters and type of parameters. The method name, number of parameters and type of parameters should be as like in Parent class.
If you are changing anything in arguments of the method of the child class, then it is not considered method overriding.

2. covariant type

If you are using the earlier version of Java 5 then the return type must have the same of override method and overridden method. From Java 5 onward, the return type can also be a subclass (subclasses are a covariant type to their parents). You can read the Covariant type with example.

3. Access modifier

The access level can’t be more restrictive than the overridden method’s access level. You can’t be more restrictive in the overridden method.

Example: If the Access Modifier of the overridden method (method of Parent class) is public then the overriding method (child class method ) cannot have a private, protected and default Access modifier because all of these three access modifiers are more restrictive than public. We can read Access Modifier from here

class ParentClass
{
   // Overridden method
   public void printData()
   {
      System.out.println("In this method we are showing the details of Parent class");
   }
}
class ChildClass extends ParentClass
{
  	 //Overriding method
	private void printData()
	{
	     System.out.println("In this method we are showing the details of child class");
	     System.out.println("We are overriding the method");
	}
   public static void main( String args[]) {
	   ChildClass childObject = new ChildClass();
      //This will call the child class method
	   childObject.printData();
   }
}

Output:
Exception in thread “main” java.lang.Error: Unresolved compilation problem: Cannot reduce the visibility of the inherited method from ParentClass at ChildClass.printData(ChildClass.java:12) at ChildClass.main(ChildClass.java:20)

4. Checked Exception handling

The overriding method can throw any unchecked exceptions, whether the overridden method is throwing any exceptions or not.

5. Checked Exception handling

The overriding method must not throw new or broader checked exceptions than the ones declared by the overridden method. You can read it in detail.

import java.io.IOException;
class ParentClass 
{  
   void color() throws IOException
   {
       System.out.println("Red");
   }  
}
class ChildClass extends ParentClass {
   //It throws a checked exception
   void color() throws IOException
   {
       System.out.println("White");
   }  
   public static void main(String args[]){  
     ParentClass obj = new ChildClass();  
       try 
       {
    obj. color();
       } 
       catch (IOException e) 
       {
    e.printStackTrace();
       } 
   } 
}

The code will run fine because the color() method of Parent class and child class is throwing a checked exception and thrown an exception by child class method should not superclass of exception thrown by Parent class.

6. final methods can’t override

final is a keyword in java used for restricting some functionalities. If we are declaring any method with final keyword it means we can’t change its implementation in child class. So, Java doesn’t permit to override any final method. You can read in detail.

Example:

  
class Parent 
{ 
    // final method in base class 
    final void showData() 
    { 
        System.out.println("This is Static method of Parent class"); 
    } 
} 
  
class Child extends Parent 
{ 
	// final method in drived class
    final void showData()
    { 
        System.out.println("This is Static method of child class"); 
    } 
} 
  
class MainClass { 
    public static void main(String[] args) 
    { 
        Parent parent = new Child(); 
        parent.showData();        
    } 
}

Output: The above example will show compilation error

7. static methods can’t override

If you have a static method in Parent class and you defining a static method with the same signature as a static method in Parent class. In this case, the Child class method would act differently.  it is known as method hiding. You can read it in detail.

  
class Parent 
{ 
    // Static method in base class 
    static void showData() 
    { 
        System.out.println("This is Static method of Parent class"); 
    } 
} 
  
class Child extends Parent 
{ 
	// static method in drived class
    static void showData()
    { 
        System.out.println("This is Static method of child class"); 
    } 
} 
  
class MainClass { 
    public static void main(String[] args) 
    { 
        Parent parent = new Child(); 
        parent.showData();      
    } 
}

Output: This is Static method of Parent class

As you know Static method can directly be called with the class name. In this example, we are calling the showData() method by reference of Parent class then compiler converts.

8. Private methods can’t override

Private methods cannot be overridden as they are local to the class. You can’t inherit the private variables and methods of the parent class.

class ParentClass
{
   private void printData()
   {
      System.out.println("In this method we are showing the details of Parent class");
   }
}
class ChildClass extends ParentClass
{
   //Overriding method
	private void printData()
	{
	     System.out.println("In this method we are showing the details of child class");
	     System.out.println("We are overriding the method");
	}
   public static void main( String args[]) {
	   ParentClass obj = new ChildClass();
      //This will call the child class method
	   obj.printData();
   }
}

Output: Exception in thread “main” java.lang.Error: Unresolved compilation problem:     The method printData() from the type ParentClass is not visible at ChildClass.main(ChildClass.java:19)

We get compiler error printData() has private access in Parent class. So the compiler tries to call Parent class function, not child class, means printData() is not overridden.

9. If any method can’t be inherited then it can’t be overridden. It may be a scenario because the protected method is inherited within the package.

10. The abstract methods must be overridden by the first concrete subclass.

11. You can’t override the constructor of the parent class. Because Constructor name must always be same as Class name.