Saturday, 12 August 2017

Method Overloading Detailed Explanation

Method Overloading:


Overloading in Java


Overloading allows different methods to have same name, but different signatures where signature can differ by number of input parameters or type of input parameters or both. Overloading is related to compile time (or static) polymorphism.
// Java program to demonstrate working of method
// overloading in Java.
public class Sum {
    // Overloaded sum(). This sum takes two int parameters
    public int sum(int x, int y) {
        return (x + y);
    }
    // Overloaded sum(). This sum takes three int parameters
    public int sum(int x, int y, int z) {
         return (x + y + z);
    }
    // Overloaded sum(). This sum takes two double parameters
    public double sum(double x, double y) {
         return (x + y);
    }  
    // Driver code
    public static void main(String args[]) {
        Sum s = new Sum();
        System.out.println(s.sum(10, 20));
        System.out.println(s.sum(10, 20, 30));
        System.out.println(s.sum(10.5, 20.5));
    }
}
Output:Output :
30
60
31.0
What is the advantage?
We don’t have to create and remember different names for functions doing the same thing. For example, in our code, if overloading was not supported by Java, we would have to create method names like sum1, sum2,… or sum2Int, sum3Int, … etc.
Can we overload methods on return type?
We cannot overload by return type. This behavior is same in C++. Refer this for details
public class Main
{
    public int foo() { return 10; }
    // compiler error: foo() is already defined
    public char foo() { return 'a'; }
    public static void main(String args[])
    {
    }
}Can we overload static methods?
The answer is ‘Yes’. We can have two ore more static methods with same name, but differences in input parameters. For example, consider the following Java program. 
Can we overload methods that differ only by static keyword?
We cannot overload two methods in Java if they differ only by static keyword (number of parameters and types of parameters is same). See following Java program for example. 
Can we overload main() in Java?
Like other static methods, we can overload main method.
// A Java program with overloaded main()
import java.io.*;
  
public class Test {
      
    // Normal main()
    public static void main(String[] args) {
        System.out.println("Hi Geek (from main)");
        Test.main("Geek");
    }
  
    // Overloaded main methods
    public static void main(String arg1) {
        System.out.println("Hi, " + arg1);
        Test.main("Dear Geek","My Geek");
    }
    public static void main(String arg1, String arg2) {
        System.out.println("Hi, " + arg1 + ", " + arg2);
    }
}Output :
Hi Geek (from main)
Hi, Geek
Hi, Dear Geek, My Geek
Does Java support Operator Overloading?
Unlike C++, Java doesn’t allow user defined overloaded operators. Internally Java overloads operators, for example + is overloaded for concatenation.

What is the difference between Overloading and Overridding?
  • Overloading is about same function have different signatures. Overriding is about same function, same signature but different classes connected through inheritance.
  • Overloading is an example of compiler time polymorphism and overriding is an example of run time polymorphism.



Different ways of Method Overloading in Java


Prerequisite- Overloading
Java can distinguish the methods with different method signatures. i.e. the methods can have same name but with different parameters list (i.e. number of the parameters, order of the parameters, and data types of the parameters) within the same class.
  • Overloaded methods are differentiated based on the number and type of the parameters passed as an arguments to the methods.
  • You can not define more than one method with the same name, Order and the type of the arguments. It would be compiler error.
  • The compiler does not consider the return type while differentiating the overloaded method. You can declare the methods with the same signature and different return type.
Why do we need Method Overloading ??
If we need to do same kind of the operation with different ways i.e. for different inputs. In the example described below, we are doing the addition operation for different inputs. It is hard to find many different meaningful names for single action.
Different ways of doing overloading methods
Method overloading can be done by changing:
  • The number of parameters in two methods.
  • The data types of the parameters of methods.
  • The Order of the parameters of methods.
Method 1: By changing the number of parameters.
import java.io.*;
  
class Addition{
   // adding two integer values.
    public int add(int a, int b){
int sum = a+b;
        return sum;
    }
      
    // adding three integer values.
    public int add(int a, int b, int c){
          
        int sum = a+b+c;
        return sum;
    }
      
}
  
class GFG {
    public static void main (String[] args) {
          
        Addition ob = new Addition();
          
        int sum1 = ob.add(1,2);
        System.out.println("sum of the two integer value :" + sum1);
        int sum2 = ob.add(1,2,3);
        System.out.println("sum of the three integer value :" + sum2);
          
    }
}Output:
sum of the two integer value :3
sum of the three integer value :6
Method 2: By changing the Data types of the parameters
import java.io.*;
  
class Addition{
      
    // adding three integer values.
    public int add(int a, int b, int c){
          
        int sum = a+b+c;
        return sum;
    }
      
    // adding three double values.
    public double add(double a, double b, double c){
          
        double sum = a+b+c;
        return sum;
    }
}
  
class GFG {
    public static void main (String[] args) {
          
        Addition ob = new Addition();
         
        int sum2 = ob.add(1,2,3);
        System.out.println("sum of the three integer value :" + sum2);
        double sum3 = ob.add(1.0,2.0,3.0);
        System.out.println("sum of the three double value :" + sum3);
          
          
    }
}Output:
sum of the three integer value :6
sum of the three double value :6.0
Method 3: By changing the Order of the parameters
import java.io.*;
  
class Geek{
      
    public void geekIdentity(String name,  int id){
          
        System.out.println("geekName :"+ name +" "+"Id :"+ id);
    }
      
    public void geekIdentity(int id, String name){
          
        System.out.println("geekName :"+ name +" "+"Id :"+ id);
    }
}
  
class GFG {
    public static void main (String[] args) {
          
        Geek geek = new Geek();
          
        geek.geekIdentity("Mohit", 1);
        geek.geekIdentity("shubham", 2);
          
    }
}Output:
geekName :Mohit Id :1
geekName :shubham Id :2
What happens when method signature is same and the return type is different?
The compiler will give error as the return value alone is not sufficient for the compiler to figure out which function it has to call. 
Only if both methods have different parameter types (so, they have different signature), then Method overloading is possible.
// Example to show error when method signature is same
// and return type is different.
import java.io.*;
class Addition
{
    // adding two integer value.
    public int add(int a, int b)
    {
         
        int sum = a+b;
        return sum;
    }
     
    // adding three integer value.
    public double add(int a, int b)
    {
        double sum = a+b+0.0;
        return sum;
    }
   
}
class GFG
{
    public static void main (String[] args)
    {
        Addition ob = new Addition();
         
        int sum1 = ob.add(1,2);
        System.out.println("sum of the two integer value :" + sum1);
         
        int sum2 = ob.add(1,2);
        System.out.println("sum of the three integer value :" + sum2);
         
    }
}Output:
16: error: method add(int,int) is already defined in class Addition
 public double add(int a, int b)
               ^
1 error

Can we Overload or Override static methods in java ?

Let us first define Overloading and Overriding.
Overriding : Overriding is a feature of OOP languages like Java that is related to run-time polymorphism. A subclass (or derived class) provides a specific implementation of a method in superclass (or base class).
The implementation to be executed is decided at run-time and decision is made according to the object used for call. Note that signatures of both methods must be same. 
Overloading: Overloading is also a feature of OOP languages like Java that is related to compile time (or static) polymorphism. This feature allows different methods to have same name, but different signatures, especially number of input parameters and type of input parameters. Note that in both C++ and Java, methods cannot be overloaded according to return type.
Can we overload static methods?
The answer is ‘Yes’. We can have two ore more static methods with same name, but differences in input parameters. For example, consider the following Java program.
// filename Test.java
public class Test {
    public static void foo() {
        System.out.println("Test.foo() called ");
    }
    public static void foo(int a) {
        System.out.println("Test.foo(int) called ");
    }
    public static void main(String args[])
    {
        Test.foo();
        Test.foo(10);
    }
}Output:
Test.foo() called 
Test.foo(int) called 
Can we overload methods that differ only by static keyword?
We cannot overload two methods in Java if they differ only by static keyword (number of parameters and types of parameters is same). See following Java program for example. This behaviour is same in C++ (See point 2 of this).
// filename Test.java
public class Test {
    public static void foo() {
        System.out.println("Test.foo() called ");
    }
    public void foo() { // Compiler Error: cannot redefine foo()
        System.out.println("Test.foo(int) called ");
    }
    public static void main(String args[]) {
        Test.foo();
    }
}
Output: Compiler Error, cannot redefine foo()Output: Compiler Error, cannot redefine foo()
Can we Override static methods in java?
We can declare static methods with same signature in subclass, but it is not considered overriding as there won’t be any run-time polymorphism. Hence the answer is ‘No’.
If a derived class defines a static method with same signature as a static method in base class, the method in the derived class hides the method in the base class.
/* Java program to show that if static method is redefined by
   a derived class, then it is not overriding. */
 
// Superclass
class Base {
     
    // Static method in base class which will be hidden in subclass
    public static void display() {
        System.out.println("Static or class method from Base");
    }
     
     // Non-static method which will be overridden in derived class
     public void print()  {
         System.out.println("Non-static or Instance method from Base");
    }
}
 
// Subclass
class Derived extends Base {
     
    // This method hides display() in Base
    public static void display() {
         System.out.println("Static or class method from Derived");
    }
     
    // This method overrides print() in Base
    public void print() {
         System.out.println("Non-static or Instance method from Derived");
   }
}
 
// Driver class
public class Test {
    public static void main(String args[ ])  {
       Base obj1 = new Derived();
        
       // As per overriding rules this should call to class Derive's static
       // overridden method. Since static method can not be overridden, it
       // calls Base's display()
       obj1.display(); 
        
       // Here overriding works and Derive's print() is called
       obj1.print();    
    }
}Output:
Static or class method from Base
Non-static or Instance method from Derived
Following are some important points for method overriding and static methods in Java.
1) For class (or static) methods, the method according to the type of reference is called, not according to the abject being referred, which means method call is decided at compile time.
2) For instance (or non-static) methods, the method is called according to the type of object being referred, not according to the type of reference, which means method calls is decided at run time.
3) An instance method cannot override a static method, and a static method cannot hide an instance method. For example, the following program has two compiler errors.
/* Java program to show that if static methods are redefined by
   a derived class, then it is not overriding but hidding. */
 
// Superclass
class Base {
     
    // Static method in base class which will be hidden in subclass
    public static void display() {
        System.out.println("Static or class method from Base");
    }
     
     // Non-static method which will be overridden in derived class
     public void print()  {
         System.out.println("Non-static or Instance method from Base");
    }
}
 
// Subclass
class Derived extends Base {
     
    // Static is removed here (Causes Compiler Error)
    public void display() {
        System.out.println("Non-static method from Derived");
    }
     
    // Static is added here (Causes Compiler Error)
    public static void print() {
        System.out.println("Static method from Derived");
   }
}
4) In a subclass (or Derived Class), we can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass methods — they are new methods, unique to the subclass.

No comments:

Post a Comment