B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Java Method Overloading | Login Technologies

Method Overloading in Java

What is Method Overloading?

Method Overloading in Java means defining multiple methods with the same name but different parameter lists in the same class.
It helps perform similar tasks with different types or numbers of inputs.

Java में Method Overloading का मतलब है एक ही class में एक जैसे नाम के multiple methods होना लेकिन उनके parameters अलग-अलग हों।
इससे हम एक जैसे काम अलग-अलग तरीकों से कर सकते हैं।

Advantages of Method Overloading

  • Improves code readability and reusability.
  • Supports compile-time polymorphism.
  • Allows calling same method name with different parameters.
  • Reduces complexity by avoiding multiple method names.
  • Code पढ़ने और reuse करने में आसान।
  • Compile-time polymorphism को support करता है।
  • एक ही नाम के method को अलग parameters के साथ call कर सकते हैं।
  • अलग-अलग नामों से बचकर code simple बनता है।

Example: Employee Class with Method Overloading

In this example, the Employee class has multiple setDetails() methods to set employee details differently.

इस उदाहरण में Employee class में कई setDetails() methods हैं जो employee की जानकारी अलग-अलग तरीकों से सेट करते हैं।

public class Employee {
    String name;
    int age;
    double salary;

    // Method 1: set only name
    void setDetails(String name) {
        this.name = name;
    }

    // Method 2: set name and age
    void setDetails(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Method 3: set name, age, and salary
    void setDetails(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    void display() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Salary: " + salary);
    }

    public static void main(String[] args) {
        Employee emp = new Employee();

        emp.setDetails("Abhishek");
        emp.display();
        System.out.println();

        emp.setDetails("Abhishek Gangwar", 30);
        emp.display();
        System.out.println();

        emp.setDetails("Abhishek Gangwar", 30, 75000.50);
        emp.display();
    }
}

Output:

Name: Abhishek
Age: 0
Salary: 0.0

Name: Abhishek Gangwar
Age: 30
Salary: 0.0

Name: Abhishek Gangwar
Age: 30
Salary: 75000.5

In the example above, the setDetails method is overloaded with different parameter lists to set employee details in various ways.

ऊपर के उदाहरण में setDetails method को अलग-अलग parameters के साथ overload किया गया है जिससे employee की जानकारी अलग-अलग तरीकों से सेट हो सकती है।