CodeGym /課程 /Java 核心 /加載類、靜態數據……

加載類、靜態數據……

Java 核心
等級 5, 課堂 7
開放

“你好,阿米戈!我聽到 Rishi 向你解釋了一些新的和令人興奮的東西?!”

“沒錯,金。”

“我的話題同樣有趣。我想告訴你類是如何加載到內存中的。”

Java 中的類是磁盤上包含字節碼的文件,字節碼是編譯後的 Java 代碼。

“是的,我記得。”

如果不需要,Java 機器不會加載它們。一旦代碼中某處調用了某個類,Java 機器就會檢查它是否已加載。如果沒有,則加載並初始化它。

初始化一個類涉及為其所有靜態變量賦值並調用所有靜態初始化塊。

“這看起來類似於在對像上調用構造函數。但是什麼是靜態初始化塊?”

“如果你需要執行複雜的代碼(例如,從文件中加載一些東西)來初始化對象,我們可以在構造函數中完成。但是,靜態變量沒有這個機會。但由於需求仍然存在,你可以向類中添加一個或多個靜態初始化塊。它們基本上等同於靜態構造函數。”

這是它的樣子:

代碼 到底發生了什麼
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
任務
Java 核心, 等級 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