CodeGym /पाठ्यक्रम /जावा कोर /कक्षाएं लोड हो रही हैं, स्थिर डेटा…

कक्षाएं लोड हो रही हैं, स्थिर डेटा…

जावा कोर
स्तर 5, सबक 7
उपलब्ध

"हैलो, एमिगो! मैंने सुना है कि ऋषि ने आपको कुछ नया और रोमांचक बताया है?"

"यह सही है, किम।"

"मेरा विषय कम दिलचस्प नहीं होगा। मैं आपको बताना चाहता हूं कि कक्षाओं को मेमोरी में कैसे लोड किया जाता है।"

जावा में कक्षाएं डिस्क पर फाइलें होती हैं जिनमें बाइटकोड होता है, जो जावा कोड संकलित होता है।

"हाँ मैं मुझे याद है।"

यदि आवश्यकता नहीं है तो जावा मशीन उन्हें लोड नहीं करती है। जैसे ही कोड में किसी क्लास को कॉल आती है, जावा मशीन यह देखने के लिए जांच करती है कि यह लोड है या नहीं। और यदि नहीं, तो यह इसे लोड और इनिशियलाइज़ करता है।

किसी वर्ग को आरंभ करने में उसके सभी स्थिर चरों को मान निर्दिष्ट करना और सभी स्थैतिक आरंभीकरण ब्लॉकों को कॉल करना शामिल है।

"ऐसा लगता है कि किसी ऑब्जेक्ट पर कन्स्ट्रक्टर को कॉल करने जैसा लगता है। लेकिन स्थिर प्रारंभिक ब्लॉक क्या है?"

"यदि आपको वस्तुओं को इनिशियलाइज़ करने के लिए जटिल कोड (उदाहरण के लिए, किसी फ़ाइल से कुछ लोड करना) निष्पादित करने की आवश्यकता है, तो हम इसे एक कंस्ट्रक्टर में कर सकते हैं। हालाँकि, स्थिर चर के पास यह अवसर नहीं है। लेकिन चूंकि आवश्यकता अभी भी बनी हुई है, आप कर सकते हैं क्लासेस में स्टैटिक इनिशियलाइज़ेशन ब्लॉक या ब्लॉक जोड़ें। वे मूल रूप से स्टैटिक कंस्ट्रक्टर्स के बराबर हैं।"

यह कैसा दिखता है:

कोड वास्तव में क्या होता है
class Cat
{
public static int catCount = 0 ;
public static String namePrefix;

static
{
Properties p = new Properties();
p.loadFromFile("cat.properties");
namePrefix = p.get("name-prefix");
}

public static int maxCatCount = 50;

static
{
Properties p = new Properties();
p.loadFromFile("max.properties");
if (p.get("cat-max") != null)
maxCatCount = p.getInt("cat-max");
}

}


class Cat
{
public static int catCount;
public static String namePrefix;
public static int maxCatCount;

//Static constructors aren't allowed in Java,
//but if they were, everything
//would look like this
public static Cat()
{
catCount = 0;

Properties p = new Properties();
p.loadFromFile("cat.properties");
namePrefix = p.get("name-prefix");

maxCatCount = 50;

Properties p2 = new Properties();
p2.loadFromFile("max.properties");
if (p2.get("cat-max")!=null)
maxCatCount = p2.getInt("cat-max");
}
}

यह बहुत कुछ वैसा ही है जैसा कि कंस्ट्रक्टर को बुलाए जाने पर होता है। मैंने इसे एक (अस्तित्वहीन) स्थिर कन्स्ट्रक्टर के रूप में भी लिखा है।

"हाँ मुझे समझ में आ गया है।"

"बहुत अच्छा।"

4
टास्क
जावा कोर, स्तर 5, सबक 7
लॉक
Code entry
Your attention, please! Now recruiting code entry personnel for CodeGym. Turn up your focus, let your fingers relax, read the code, and then... type it into the appropriate box. Code entry is far from a useless exercise, though it might seem so at first glance: it allows a beginner to get used to and remember syntax (modern IDEs seldom make this possible).
टिप्पणियां
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION