example of method overloading in java

Example 1: what is method overloading and method overriding in Java?

Method overloading is providing two separate methods in a class with the same name but different arguments, while the method return type may or may not be different, which allows us to reuse the same method name.

Method overriding means defining a method in a child class that is already defined in the parent class with the same method signature, same name, arguments, and return type

Example 2: program for method overloading in java

class Calculate
{
  void sum (int a, int b)
  {
    System.out.println("sum is"+(a+b)) ;
  }
  void sum (float a, float b)
  {
    System.out.println("sum is"+(a+b));
  }
  Public static void main (String[] args)
  {
    Calculate  cal = new Calculate();
    cal.sum (8,5);      //sum(int a, int b) is method is called.
    cal.sum (4.6f, 3.8f); //sum(float a, float b) is called.
  }
}

Example 3: method overloading

//https://www.geeksforgeeks.org/overloading-in-java/
// 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)); 
    } 
}

Example 4: where we use method overloading in java

Method overloading is providing 
two separate methods in a class 
with the same name but different arguments,
while the method return type 
may or may not be different, which
allows us to reuse the same method name.
In my framework==
I use implicit wait in Selenium. Implicit wait
is an example of overloading. In Implicit wait
we use different time stamps such as SECONDS, MINUTES, HOURS etc.,
A class having multiple methods with
same name but different parameters 
is called Method Overloading

Tags:

Cpp Example