Method Overloading in JAVA \ BCA SEM 04 JAVA BKNMU JUNAGADH

Method Overloading in Java

Method Overloading in Java

Method overloading allows a class to have multiple methods with the same name but different parameter lists.

Example


// Java program demonstrating method overloading
public class OverloadingExample {
    // Method with no parameters
    public void display() {
        System.out.println("Display method with no arguments.");
    }

    // Method with one parameter
    public void display(int a) {
        System.out.println("Display method with one argument: " + a);
    }

    // Method with two parameters
    public void display(int a, String b) {
        System.out.println("Display method with two arguments: " + a + ", " + b);
    }

    // Method with different parameter order
    public void display(String b, int a) {
        System.out.println("Display method with reversed arguments: " + b + ", " + a);
    }

    public static void main(String[] args) {
        OverloadingExample obj = new OverloadingExample();
        
        obj.display();
        obj.display(10);
        obj.display(20, "Hello");
        obj.display("World", 30);
    }
}
    

Output


Display method with no arguments.
Display method with one argument: 10
Display method with two arguments: 20, Hello
Display method with reversed arguments: World, 30
    

Explanation

  • The display() method is overloaded with different parameter lists.
  • The appropriate method is called based on the arguments passed.
  • Method overloading is an example of compile-time polymorphism.

Post a Comment

Thanks for comment.

Previous Post Next Post