Method overriding means defining a method with the same name and same arguments in a child class as defined in a super(or parent) class.
Remember that both number and type of arguments must match, only then a method will be considered as overriden.
Overriding can only take place between parent and child classes where inheritance is present.

Use of method overriding
Following are the important applications of method overriding in java.

  • Separate method implementation in child class
    Overriding is required when a specific implementation or functionality of a method is needed in a child class.
    Suppose you have a TextFileReader class which has a method readFile(String file) to read a text file.
    Now, there is a CSVFileReader class which is a child class of TextFileReader.
    This class should also has a readFile method(inherited from its parent class).
    But, the logic to read a CSV file is different from a text file.
    Thus, it should also define its own readFile method.
  • Runtime polymorphism
    When a child class overrides the parent class method, then it has two methods with same name:
    1. one that it inherits from parent class, and
    2. other that it implements on its own.Method that is invoked is decided at run time or when the program is executed based on the actual object on which the method is called.
    Thus, if the method name is print, then

    Parent p = new Parent();
    p.print();    // parent class print method is called

    Parent p = new Child();
    p.print();    // child class print method is called

    Child c = new Child();
    p.print();    // child class print method is called

    Child class method will be invoked when the object is of child class even if the reference is of parent.
    Parent method will be invoked only when both reference and object are of parent class.
    Hence, method overriding lets you achieve runtime polymorphism.

Method Overriding example
Below is a practical example of method overriding in java.
It involves two class, a TextFileReader and a CSVFileReader as explained above.

/**
 * Main class
 *
 */
public class OverridingDemo {

   public static void main(String[] args) {
	// create object of parent class
	TextFileReader reader = new TextFileReader();
	// call method
	reader.readFile("abc.txt");
	
	// create child class object
	reader = new CSVFileReader();
	// call method
	reader.readFile("def.csv");
   }
}

class TextFileReader {
	
   /**
    * Parent class method
    * @param fileName
    */
   public void readFile(String fileName) {
	System.out.println("Reading text file...");
   }
}
class CSVFileReader extends TextFileReader {
   /** 
    * Overridden method of parent class
    */
   public void readFile(String fileName) {
	System.out.println("Reading CSV file...");
   }
}

Below is the output

Reading text file…
Reading CSV file…

Output clearly shows that invoked method depends on the actual object that is used to call the method.


Calling parent class method from child method
Many times the overridden method in child needs to invoke the parent method.
This might be in a situation that overridden method extends the functionality of parent method and before it starts executing, parent method should be executed.

In these cases, it becomes necessary to invoke parent method from overridden method.
A parent class method can be called from a child class using super keyword followed by the name of method and dot operator as shown below.

public void readFile(String fileName) {
   // call parent class method
   super.readFile(fileName);
   System.out.println("Reading CSV file...");
}

Overriding rules in java
Just defining a method with same name in a child class is not considered overriding. An overridden methods must follow below rules.

  • Method arguments
    Number and type of arguments of overridden method(in child class) should be same as the method being overridden otherwise it will be considered as method overloading, not overriding.
  • Exceptions
    Overridden method can only throw exceptions if parent method throws it.
    If a parent method does not throw any exceptions then overridden method can only throw unchecked or runtime exceptions.If the parent method throws an exception, then overridden method can throw the same exception or a sub class of that exception or throw no exception at all.
    Example, if parent method throws java.lang.IOException, then overridden method can only throw the same exception or java.io.FileNotFoundException since it is a child class of java.io.IOException.
  • private methods cannot be overridden
    Methods that are marked private are visible only inside the same class.
    Thus, if a parent method is marked private, then it will not be visible to the child class.In that case, if the child class declares a method with same name, then it will not be considered as overriding but a separate method.
  • Access modifier restriction
    Overridden method can have the same access modifier or one that is less restricted as compared to the parent class method.
    Less restricted means one which does not reduce visibility of method.Below is a table of valid access specifier for overridden method corresponding to the parent method.

    Parent method access specifierValid child method access specifiers
    publicpublic
    protectedprotected, public
    default(no access specifier)default, protected, public

    where default means no access specifier is present.

  • Return types
    Overridden method may have the same return types as the parent method.
    If parent method returns an object, then overridden method can return an object of same type or of a sub-type.
    Example,
    if a parent method returns an object of Animal, then overridden method can return an Animal object or an object of Cat or Dog where both these are sub-classes of Animal.
    These are called covariant returns.

How to prevent method overriding in java
Often we create a method in a class and we do not want its sub classes to override the method to provide a separate implementation.
This is because the developer of method knows that a particular method should only be implemented the way he did.

There is a provision in java to stop a method from being overridden by marking it as final.
If a method is marked final and someone tries to override it, then straight away compiler flags an error.

Cannot override the final method from <class name>

final keyword should be placed before the return type of method.
Example of final method definitions are

public final void readFile() { // method body }
final public void readFile(){ // method body }
final void readFile(){ // method body }

Can we override static method
static method belongs to a class and not to any particular object hence they can not be overridden.
If you create static methods with same name in both parent and child classes and try to call it, then the method will be called on the basis of reference which was used to call it irrespective of the actual object.
If the reference is of parent class, then parent class method will be called even if the object is of child class.
This is in contrast to non-static methods where child class method will be invoked in such case.
If the reference is of child class, then child class method will be called.
Example,

/**
 * Main class
 *
 */
public class OverridingDemo {

   public static void main(String[] args) {
	// create object of parent class
	TextFileReader reader = new TextFileReader();
	// call method
	reader.readFile("abc.txt");
	
	// create child class object
	reader = new CSVFileReader();
	// call method
	reader.readFile("def.csv");
   }
}

class TextFileReader {
	
   /**
    * Parent class method
    * @param fileName
    */
   public static void readFile(String fileName) {
	System.out.println("Reading text file...");
   }
}
class CSVFileReader extends TextFileReader {
   /** 
    * Overridden method of parent class
    */
   public static void readFile(String fileName) {
	System.out.println("Reading CSV file...");
   }
}

In above example, both methods are of the same name with same number and type of arguments and are preceded with static keyword.

This program when executed gives the following output

Reading text file…
Reading text file…

See, child class method is never called since both the times the reference is of parent class.
This is also called method hiding as super class method hides the child class method.
Can we override constructor
A constructor name should match name of the class.
Thus, child class constructor would have the name of child class and parent class constructor will have its name while overridden methods should have the same name.
Due to this reason, constructors can not be overridden.
Can we override abstract methods
Abstract methods are incomplete methods and they are meant to be overridden in a child class.
If a parent class contains an abstract method, then child class should override it else child class should also be marked abstract class.
Override annotation
@Override annotation
was introduced in java 1.5 version and serves as a compile time check.
If you annotate a method with @Override annotation then compiler checks it to be a proper overriding such that the overridden method follows all the rules mentioned above.

Thus, the compiler will verify

  • Method name, number and type of arguments match with parent class method.
  • If the parent method does not throw and checked exception, then overridden method also does not throw any checked exception.
  • If the parent method throws a checked exception, then overridden method throws the same or sub-type of that exception.
  • Return type of overridden method matches the parent method.
  • Access specifier of overridden method is not more restrictive than parent method.

If any of the above checks fail, then compiler shows an error.

Thus, if the developer intends to override a method but mistakenly changes the argument type(which will make the method overloaded), then @Override annotation comes handy and can save him from unexpected behavior at run time.
That is all on java method overriding in this article.

Leave a Reply