What are the rules on method overriding in Java?

Java 8Object Oriented ProgrammingProgramming

If superclass and subclass have methods with same name including parameters. JVM calls the respective method based on the object used to call the method.i.e. if the object used to call the method is of superclass type the method of the superclass is executed.

Or, if the object is of the type subclass then the method of the superclass is executed.

Example

 Live Demo

class Super{
   public void sample(){
      System.out.println("Method of the Super class");
   }
}
public class MethodOverriding extends Super {
   public void sample(){
      System.out.println("Method of the Sub class");
   }
   public static void main(String args[]){
      MethodOverriding obj = new MethodOverriding();
      obj.sample();
   }
}

Output

Method of the Sub class

Rules to be followed while overriding methods

While overriding you need to keep the following points in mind −

  • Both methods must have same name, same parameters and, same return type else they both will be treated as different methods.
  • The method in the child class must not have higher access restriction than the one in the super class. If you try to do so it raises a compile time exception.

Example

class Super{
   void sample(){
      System.out.println("Method of the Super class");
   }
}
public class MethodOverriding extends Super {
   private void sample(){
      System.out.println("Method of the Sub class");
   }
   public static void main(String args[]){
      MethodOverriding obj = new MethodOverriding();
      obj.sample();
   }
}

Compile time error

MethodOverriding.java:7: error: sample() in MethodOverriding cannot override sample() in Super
private void sample(){
             ^
   attempting to assign weaker access privileges; was package
1 error
  • If the super-class method throws certain exception, the method in the sub-class should throw the same exception or its sub type (can leave without throwing any exception). It should not throw a broader exception. If it does a compile time error is generated.

Example

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

abstract class Super{
   public String readFile(String path)throws FileNotFoundException{
      throw new FileNotFoundException();
   }
}
public class ExceptionsExample extends Super{
   @Override
   public String readFile(String path)throws IOException {
      //method body ......
   }
}

Compile time error

On compiling, the above program gives you the following output −

ExceptionsExample.java:13: error: readFile(String) in ExceptionsExample cannot override readFile(String) in Sup
public String readFile(String path)throws IOException {
              ^
overridden method does not throw IOException
raja
Published on 08-Jul-2019 15:46:41
Advertisements