Java Method Overloading

🔹 Java Method Overloading

Method Overloading in Java allows multiple methods in the same class to have the same name but different parameters.
It is a compile-time polymorphism technique.


✅ 1. Rules of Method Overloading

  1. Methods must have the same name.

  2. Methods must have different parameters:

    • Different number of parameters, or

    • Different type of parameters, or

    • Both

  3. Return type alone cannot distinguish overloaded methods.

  4. Methods can have different access modifiers.


✅ 2. Example 1: Different Number of Parameters

public class Main {
static int add(int a, int b) {
return a + b;
}

static int add(int a, int b, int c) {
return a + b + c;
}

public static void main(String[] args) {
System.out.println(add(5, 10)); // 15
System.out.println(add(5, 10, 15)); // 30
}
}


✅ 3. Example 2: Different Parameter Types

public class Main {
static int multiply(int a, int b) {
return a * b;
}

static double multiply(double a, double b) {
return a * b;
}

public static void main(String[] args) {
System.out.println(multiply(5, 4)); // 20
System.out.println(multiply(3.5, 2.0)); // 7.0
}
}


✅ 4. Example 3: Mixed Parameters

public class Main {
static void greet(String name) {
System.out.println("Hello, " + name + "!");
}

static void greet(String name, int age) {
System.out.println("Hello, " + name + "! You are " + age + " years old.");
}

public static void main(String[] args) {
greet("Alice"); // Hello, Alice!
greet("Bob", 25); // Hello, Bob! You are 25 years old.
}
}


✅ 5. Why Use Method Overloading?

  • Improves code readability.

  • Avoids writing multiple method names for similar tasks.

  • Enables flexible methods to handle different data types and arguments.


🧠 Key Points

Feature Description
Method Name Same for all overloaded methods
Parameters Must differ in type, number, or both
Return Type Can be different but cannot alone define overloading
Compile-Time Polymorphism Overloading is resolved during compilation

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *