Tutorialspoint

1 Answer
Vikyath Ram

A class can have multiple methods with the same name but the parameter list of the methods should not be the same. This is known as method overloading. Method overloading is somewhat similar to constructor overloading.

A program that demonstrates this is given as follows:

Example

 Live Demo

class PrintValues {
   public void print(int val) {
      System.out.println("The value is: " + val);
   }
   public void print(double val) {
      System.out.println("The value is: " + val);
   }
   public void print(char val) {
      System.out.println("The value is: " + val);
   }
}
public class Demo {
   public static void main(String[] args) {
      PrintValues obj = new PrintValues();
      obj.print(7);
      obj.print(19.3);
      obj.print('A');
   }
}

Output

The value is: 7
The value is: 19.3
The value is: A

Now let us understand the above program.

The PrintValues class is created with three methods print() in the implementation of method overloading. One of these takes a parameter of type int, another takes a parameter of type double and the last takes a parameter of type char. A code snippet which demonstrates this is as follows:

class PrintValues {
   public void print(int val) {
      System.out.println("The value is: " + val);
   }
   public void print(double val) {
      System.out.println("The value is: " + val);
   }
   public void print(char val) {
      System.out.println("The value is: " + val);
   }
}

In the main() method, object obj of class PrintValues is created and the print() method is called three times with parameters 7, 19.3 and ‘A’ respectively. A code snippet which demonstrates this is as follows:

public class Demo {
   public static void main(String[] args) {
      PrintValues obj = new PrintValues();
      obj.print(7);
      obj.print(19.3);
      obj.print('A');
   }
}

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.