Difference between Method Overloading and Method Overriding

Method Overloading and Overriding help us to achieve polymorphism, which is one of the features of Object-Oriented-programming language

1. Method Overloading

  • Method overloading is a oops concepts in which a class can have two or more methods with same name but with different parameter
  • It is also called static polymorphism or time binding or early binding
  • It is implemented during compile time
  • There are two ways to overload method in java :
    1.Different Number of Arguments
    2.Different Data Types

Example

public class MethodOverloading 
  {
		public static void main(String[] args) 
	{
			MethodOverloading a = new MethodOverloading ();
			a.age(5);
			a.age(18, "CSE");
			a.display('H');
			a.display(12);	
	}
		public void age(int a)
		{
			System.out.println("The age is:" + a);
		}
		public void age(int a, String c)
		{
			System.out.println("The age is:" + a +" Name:" + c);
		}
		public void display(int a)
		{
			System.out.println("The age is:" + a);
		}
		public void display(char a)
		{
			System.out.println("Name is:" + a);
		}
		

}
    

2. Method Overriding

  • if sub class has the same method as declared in parent class it is called method overriding
  • it is also called dynamic binding/ dynamic polymorphism
  • It is implemented during run time

Example

class baby 
{
	
	void display()
	{
		System.out.println("This is the Child class");
	}
	
}
public class MethodOverriding extends baby
{
	public static void main(String[] args) 
	{
		 MethodOverriding obj = new  MethodOverriding ();
		 obj.display();

	}
	void display()
	{
		super.display();
		System.out.println("This is the parent class");
	}
}

1 comment: