What are the three ways to achieve overloading in Java?

0166

In Java, method overloading can be achieved in three main ways:

  1. By Changing the Number of Parameters: You can create multiple methods with the same name but different numbers of parameters.

    public class OverloadExample {
        void display(int a) {
            System.out.println("Integer: " + a);
        }
        
        void display(int a, String b) {
            System.out.println("Integer: " + a + ", String: " + b);
        }
    }
  2. By Changing the Type of Parameters: You can overload methods by changing the types of parameters.

    public class OverloadExample {
        void display(int a) {
            System.out.println("Integer: " + a);
        }
        
        void display(String b) {
            System.out.println("String: " + b);
        }
    }
  3. By Changing the Order of Parameters: You can also overload methods by changing the order of parameters if they have different types.

    public class OverloadExample {
        void display(String b, int a) {
            System.out.println("String: " + b + ", Integer: " + a);
        }
        
        void display(int a, String b) {
            System.out.println("Integer: " + a + ", String: " + b);
        }
    }

These methods allow you to define multiple methods with the same name but different signatures, enabling more flexible code.

0 Comments

no data
Be the first to share your comment!