Class और Object
Class define करती है कि object के पास क्या properties (fields) और क्या behavior (methods) होंगे।
Object class का एक "instance" होता है — real चीज़ जिसको तुम use कर सकते हो, अपनी values के साथ।
class Car {
String color;
void drive() { System.out.println(color + " car driving!"); }
}
Car myCar = new Car();
myCar.color = "Red";
myCar.drive();- Class = blueprint
- Object = real instance
- new keyword से object बनता है
Fields (variables) class की "state" होते हैं — data जो object अपने पास रखता है (जैसे Car का color, speed)। Methods "behavior" होते हैं — काम जो object कर सकता है (जैसे Car का drive(), brake())। एक class दोनों का combination होती है: "ये चीज़ क्या है" (fields) और "ये क्या कर सकती है" (methods)।
Fields को "attributes" या "properties" भी कहते हैं, और methods को "behaviors" या "functions"। Real-world modeling में, तुम जब भी एक class design करो, ख़ुद से दो सवाल पूछो: "इस चीज़ के पास क्या information होगी?" (fields) और "ये चीज़ क्या-क्या कर सकती है?" (methods)।
एक ही class से बनाए गए अलग-अलग objects अपनी-अपनी independent field values रखते हैं — एक object की value change करने से दूसरे object पर कोई असर नहीं पड़ता। ये इसलिए होता है क्योंकि हर "new" call से एक नया, अलग memory block (Heap में) allocate होता है।
Static fields इस rule का exception हैं (जैसे "this-static" topic में detail से देखोगे) — वो class-level होती हैं, इसलिए सब objects में shared रहती हैं, एक change करने से सबमें दिखता है।
Car car1 = new Car();
Car car2 = new Car();
car1.color = "Red";
car2.color = "Blue"; // car1.color abhi bhi "Red" hi hai
System.out.println(car1 == car2); // false — do alag objects hainजब तुम "new Car()" लिखते हो, exactly ये होता है step-by-step: (1) Heap memory में जगह allocate होती है object (उसके सारे instance fields) के लिए, (2) fields को default values मिलती हैं (0, null, false), (3) constructor चलता है जो fields को meaningful starting values देता है, (4) एक "reference" (memory address) return होता है जो variable (जो ख़ुद Stack में होता है, अगर local variable हो) में store होता है।
इसलिए variable ख़ुद object नहीं होता — वो सिर्फ़ एक reference/address होता है जो Heap में पड़ी असली चीज़ की तरफ़ point करता है। यही वजह है कि object assign करने पर (car2 = car1) दोनों variables same object को point करने लगते हैं (copy नहीं बनती, सिर्फ़ address copy होता है) — इसे "aliasing" कहते हैं।
| Stack | Heap | |
|---|---|---|
| क्या store होता है | Local variables, references | Actual objects, instance fields |
| Lifetime | Method ख़त्म, गया | जब तक कोई reference बचे, GC तक |
| Speed | Fast | थोड़ा slow (GC overhead) |