Method overriding in java example

  • Declaring a method in sub class which is already present in parent class is known as method overriding.
  • Overriding is done so that a child class can give its own implementation to a method which is already provided by the parent class.
  • In this case the method in parent class is called overridden method and the method in child class is called overriding method.

Example

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();
}
}

Use of Method Overriding

  • Method overriding is used to provide specific implementation of a method that is already provided by its super class.
  • Method overriding is used for runtime polymorphism

Rules for Method Overriding

  • method must have same name as in the parent class
  • method must have same parameter as in the parent class.

Difference between Method Overloading and Method Overriding

Method Overloading Method Overriding
Whenever same method or Constructor is existing multiple times within a class either with different number of parameter or with different type of parameter or with different order of parameter is known as Overloading. Whenever same method name is existing multiple time in both base and derived class with same number of parameter or same type of parameter or same order of parameters is known as Overriding.
Arguments of method must be different at least arguments. Argument of method must be same including order.
Method signature must be different. Method signature must be same.
Private, static and final methods can be overloaded. Private, static and final methods can not be override.
Access modifiers point of view no restriction. Access modifiers point of view not reduced scope of Access modifiers but increased.
Also known as compile time polymorphism or static polymorphism or early binding. Also known as run time polymorphism or dynamic polymorphism or late binding.