Method overloading in Java

 

๐Ÿ”ท Method Overloading

✅ What is Method Overloading?

Method Overloading is a feature in Java where a class can have multiple methods with the same name but different parameter lists (type, number, or order).

It is a form of compile-time polymorphism.


๐Ÿง  Why Use Method Overloading?

  • To perform similar operations in different ways.

  • Improves code readability and reusability.


✅ Rules for Overloading

  • Methods must have different parameter lists.

  • Can have different return types, but return type alone is not enough to overload a method.


๐Ÿงช Example:


class Calculator { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } int add(int a, int b, int c) { return a + b + c; } } public class Main { public static void main(String[] args) { Calculator c = new Calculator(); System.out.println(c.add(2, 3)); // 5 System.out.println(c.add(2.5, 3.5)); // 6.0 System.out.println(c.add(1, 2, 3)); // 6 } }

Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Java Compiler and Java Virtual Machine