Method Overloading

  • Method overloading is a mechanism through which we can define multiple methods with the same name within the same class
  • Methods share similar name but number of arguments and data type will be differ.
  • Method overloading is one of the ways to implement polymorphism.
  • Java matches number of arguments and data types to determine which version of the overloaded method to call whenever an overloaded method is called.
  • So, overloaded method must differ in data type and / or number of arguments. Only return type alone is not sufficient to determine the appropriate version for the method call.
  • We can also overload Constructor like a normal method

Example:

class A
{
   void display()
   {
     System.out.println("display() called");
   }
   void display(int i)
   {
     System.out.println("display(int) called");
   }
   void display(inti,int j)
   {
     System.out.println("display(int,int) called");
   }
   void display(double i)
   {
     System.out.println("display(double) called");
   }
}

class OverloadDemo
{
   public static void main(String args[])
   {
     A a=new A();
     a.display();
     a.display(5);
     a.display(5,10);
     a.display(10.0);
   }
}

 Method Overriding

  • In a class hierarchy, when a method in a subclass has the same name with number of arguments and data type, then the method in the subclass is said to override the method in the Super class.
  • When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the sub class. The version of the method defined by the super class will be hidden.

Example:

class A
{
   int i,j;
   A(int a, int b)
   {
      i=a;
      j=b;
   }
   void show()
   {
      System.out.println("I and j:" +i +" " +j);
   }
}

class B extends A
{
   int k;
   B(int a, int b, int c)
   {
     super(a,b);
     k=c;
   }
   void show()
   {
     System.out.println("k="+k);
   }
}

class Override
{
   public static void main(String args[])
   {
      B subob= new B(10,20,30);
      subob.show();
   }
}