OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 12 : Overloading Methods in Java

 

Unit - 2

Topic - 12 : Overloading Methods in Java

In Java, it is possible to define two or more methods within the same class that share the same name — as long as their parameter lists are different.

This is called Method Overloading, and it’s one way Java implements polymorphism.


Rules for Method Overloading

  1. Methods must have the same name.

  2. Parameter lists must differ (different number or type of parameters).

  3. Return type can be the same or different — but it alone cannot distinguish overloaded methods.


Example: Method Overloading

// Demonstrate method overloading class OverloadDemo { // No parameters void test() { System.out.println("No parameters"); } // One integer parameter void test(int a) { System.out.println("a: " + a); } // Two integer parameters void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } // One double parameter (returns double) double test(double a) { System.out.println("double a: " + a); return a * a; } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; // Call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); } }

Output:

No parameters a: 10 a and b: 10 20 double a: 123.25 Result of ob.test(123.25): 15190.5625

Explanation

  • The method test() is defined four times with different parameter lists.

  • Java decides which method to call at compile time based on the number and type of arguments.

  • This is compile-time polymorphism.


Key Benefits of Method Overloading:

  • Improves code readability.

  • Allows same operation name with different input types.

  • Makes the program flexible and easy to maintain.

Comments

Popular posts from this blog

Career Guide - B.Tech Students

Artificial Intelligence - UNIT - 1 Topic - 1 : Introduction to AI (Artificial Intelligence)

Financial Aid for Students: Scholarships from Government, NGOs & Companies