Nesting Method and Method Overloading in Java जावा में नेस्टिंग ऑफ मेथड्स और मेथड ओवरलोडिंग

Nesting of Methods:-

When one method of a class calls another method of the same class using just its name, this is called nesting of methods. This allows internal functionality reuse within the same class.

जब एक मेथड, उसी क्लास की किसी अन्य मेथड को केवल उसके नाम का उपयोग करके कॉल करता है, तो इसे "नेस्टिंग ऑफ मेथड्स" कहा जाता है। इससे एक ही क्लास के भीतर मेथड की पुनः उपयोगिता (reuse) संभव होती है।

Example:

class NestedMethods {
private int a, b;
NestedMethods(int m, int n) {
a = m;
b = n;
}
int largest() {
if (a > b) return a;
else return b;
}
void display() {
int l = largest(); // Method nesting
System.out.println("The Greatest Number is : " + l);
}
}
public class nested_method_example {
public static void main(String args[]) {
NestedMethods obj = new NestedMethods(15, 36);
obj.display();
}
}

Method Overloading:-

Method overloading allows multiple methods to have the same name in a class, provided their parameter types or number of parameters are different. It increases code readability and flexibility. Constructor overloading is a type of method overloading.

एक ही नाम की दो या दो से अधिक मेथड्स को एक ही क्लास में परिभाषित किया जा सकता है, बशर्ते उनके पैरामीटर की संख्या या डेटा प्रकार अलग हों। इसे "मेथड ओवरलोडिंग" कहा जाता है। इससे कोड की पठनीयता और लचीलापन बढ़ता है। कंस्ट्रक्टर ओवरलोडिंग, मेथड ओवरलोडिंग का ही एक प्रकार है।

✅ Method Overloading by Changing Data Type

You can overload a method by changing the type of parameters.

आप पैरामीटर के डेटा टाइप को बदलकर मेथड को ओवरलोड कर सकते हैं।

int display(int x)
double display(double y)

✅ Method Overloading by Changing Number of Parameters

Another way is to change the number of arguments passed.

दूसरा तरीका है – मेथड के पैरामीटर की संख्या बदलकर।

int display(int x)
float display(float x, float y)

✅ Example of Method Overloading

class Sample {
int display(int x) {
return x;
}
double display(double y) {
return y;
}
float display(float x, float y) {
return (x + y);
}
public static void main(String args[]) {
Sample s = new Sample();
System.out.println("Value of x : " + s.display(2));
System.out.println("Value of y : " + s.display(7.5));
System.out.println("Value of x+y : " + s.display(7.5f, 9.0f));
}
}

Output:

Value of x : 2
Value of y : 7.5
Value of x+y : 16.5

Comments

Popular posts from this blog

What is a Web Browser? वेब ब्राउज़र क्या है?

Java's Support System जावा का सहयोगी तंत्र

The Internet and Java इंटरनेट और जावा का सम्बन्ध