Java Method Overriding

Method overriding is a feature which allow a subclass to rewrite the implementation of a method already provided by the super class. The overriding is used to define a behavior that is specific to the sub class. When a class inherits a method then there is possibility to override the functionality of that method which means it was not marked final in super class.

Method Overriding Example

class Employee{

//defining office timing for all employees

public void OfficeTiming(){

System.out.println(“The office timing is 9am to 5pm”);

}

}

public class CustomerServiceRepresentative extends Employee{

//redefining office timing for customer service representatives

public void OfficeTiming(){

System.out.println(“The office timing is 6am to 2pm”);

}

public static void main(String args[]){

CustomerServiceRepresentative emp_csr = new CustomerServiceRepresentative();

emp_csr.OfficeTiming();

}

}

Output

The office timing is 6am to 2pm

Method Overriding Rules

  • The method name should be exactly the same as of overridden method
  • The method return type should be same or sub type of overridden method’s return type
  • The argument list and type should be exactly same as of overridden method
  • The access level should not be more restrictive than access level of overridden method
  • The method should not be written final

Leave a Reply

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