Method Kya Hota Hai?
Method Java mein ek block of code hota hai jo koi specific task ko perform karta hai. Jab bhi aapko kisi kaam ko baar-baar perform karna ho, toh use method mein daal dete hain.
Java mein har action – jaise print karna, calculate karna, ya display karna – ek method ke through hi hota hai.
Method Declaration (Syntax)
returnType methodName(parameters) {
// method body
}
Example:
int add(int a, int b) {
return a + b;
}
Yahaan:
int
= return type (method kya return karega)add
= method ka naam(int a, int b)
= parameters (input values)return a + b;
= return statement (output)
Method Calling
Ek baar method define ho jaaye, toh aap use object ke through ya direct (agar static ho) call kar sakte ho.
Example:
class Calculator {
int square(int x) {
return x * x;
}
}
class Main {
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.square(5)); // Output: 25
}
}
Method Signature Kya Hota Hai?
Method Signature = method ka naam + parameters ka type & order
int add(int a, int b) // method signature: add(int, int)
- Return type signature ka part nahi hota.
- Signature compiler ko batata hai ki kaunsa method call karna hai.
Method Overloading in Java
Definition:
Method Overloading ka matlab hai ek hi method ka naam rakhna, lekin different parameters ke saath.
Same method name, different input = different behavior
Example:
class Print {
void show(String msg) {
System.out.println("Message: " + msg);
}
void show(int number) {
System.out.println("Number: " + number);
}
}
Output:
Message: Hello
Number: 100
How Compiler Chooses Correct Method?
Compiler check karta hai:
- Method ka naam
- Parameter ki count, type aur order
Agar exact match milta hai, woh method call hota hai.
Method Overloading Notes:
- Return type alag hone se method overload nahi hota.
- Parameters alag hone chahiye (type ya count).
- Overloading compile-time polymorphism ka example hai.
Invalid Example:
int show(int x) { }
String show(int x) { } // Not allowed (only return type is different)
Real-Life Analogy
Socho ek ATM machine hai:
withdraw(int amount)
– withdraw fixed amountwithdraw(int amount, String mode)
– withdraw using mode like cash/card
Dono ka naam same hai, kaam thoda different. That’s method overloading.
Summary
- Method Declaration: Kaise method define hota hai
- Method Signature: Name + parameters (type & order)
- Method Overloading: Same method name, different parameters
- Not Overloading: Agar sirf return type alag ho
Comments