CodeGym /コース /Java コア /クラス、静的データをロードしています...

クラス、静的データをロードしています...

Java コア
レベル 5, レッスン 7
使用可能

「こんにちは、アミーゴ! リシが何か新しくて刺激的なことを説明してくれたと聞きました?!」

「その通りです、キムさん」

「私のトピックも同様に興味深いものになります。クラスがどのようにメモリにロードされるかについてお話したいと思います。」

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