CodeGym /కోర్సులు /జావా కోర్ /తరగతులు, స్టాటిక్ డేటా లోడ్ అవుతోంది...

తరగతులు, స్టాటిక్ డేటా లోడ్ అవుతోంది...

జావా కోర్
స్థాయి, పాఠం
అందుబాటులో ఉంది

"హలో, అమిగో! రిషి మీకు కొత్త మరియు ఉత్తేజకరమైన విషయాన్ని వివరించినట్లు నేను విన్నాను?!"

"అది నిజమే, కిమ్."

"నా అంశం తక్కువ ఆసక్తికరంగా ఉండదు. తరగతులు మెమరీలోకి ఎలా లోడ్ చేయబడతాయో నేను మీకు చెప్పాలనుకుంటున్నాను."

జావాలోని క్లాసులు అనేవి డిస్క్‌లో బైట్‌కోడ్‌ని కలిగి ఉన్న ఫైల్‌లు, ఇది జావా కోడ్‌ని కంపైల్ చేస్తుంది.

"అవును, నాకు గుర్తుంది."

జావా యంత్రం అవసరం లేకుంటే వాటిని లోడ్ చేయదు. కోడ్‌లో ఎక్కడో తరగతికి కాల్ వచ్చిన వెంటనే, జావా మెషీన్ అది లోడ్ చేయబడిందో లేదో తనిఖీ చేస్తుంది. మరియు లేకపోతే, అది లోడ్ అవుతుంది మరియు ప్రారంభిస్తుంది.

ఒక తరగతిని ప్రారంభించడం అనేది దాని స్టాటిక్ వేరియబుల్స్ అన్నింటికీ విలువలను కేటాయించడం మరియు అన్ని స్టాటిక్ ఇనిషియలైజేషన్ బ్లాక్‌లను కాల్ చేయడం.

"ఇది ఒక వస్తువుపై కన్‌స్ట్రక్టర్‌ని పిలుస్తున్నట్లు కనిపిస్తోంది. అయితే స్టాటిక్ ఇనిషియలైజేషన్ బ్లాక్ అంటే ఏమిటి?"

"ఆబ్జెక్ట్‌లను ప్రారంభించేందుకు మీరు కాంప్లెక్స్ కోడ్‌ను (ఉదాహరణకు, ఫైల్ నుండి ఏదైనా లోడ్ చేయడం) అమలు చేయవలసి వస్తే, మేము దానిని కన్స్ట్రక్టర్‌లో చేయగలము. అయితే, స్టాటిక్ వేరియబుల్స్‌కు ఈ అవకాశం లేదు. కానీ అవసరం ఇంకా మిగిలి ఉన్నందున, మీరు చేయవచ్చు తరగతులకు స్టాటిక్ ఇనిషియలైజేషన్ బ్లాక్ లేదా బ్లాక్‌లను జోడించండి. అవి ప్రాథమికంగా స్టాటిక్ కన్‌స్ట్రక్టర్‌లకు సమానం."

ఇది ఇలా కనిపిస్తుంది:

కోడ్ నిజంగా ఏమి జరుగుతుంది
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
టాస్క్
జావా కోర్, స్థాయి, పాఠం
లాక్ చేయబడింది
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