[英]Really simple java syntax clarification
我從未學習過Java,但是我需要了解以下代碼的含義,主要的問題是花括號:
/**
* This Universe uses the full HashLife algorithm.
* Since this algorithm takes large steps, we have to
* change how we increment the generation counter, as
* well as how we construct the root object.
*/
public class HashLifeTreeUniverse extends TreeUniverse {
public void runStep() {
while (root.level < 3 ||
root.nw.population != root.nw.se.se.population ||
root.ne.population != root.ne.sw.sw.population ||
root.sw.population != root.sw.ne.ne.population ||
root.se.population != root.se.nw.nw.population)
root = root.expandUniverse() ;
double stepSize = Math.pow(2.0, root.level-2) ;
System.out.println("Taking a step of " + nf.format(stepSize)) ;
root = root.nextGeneration() ;
generationCount += stepSize ;
}
{
root = HashLifeTreeNode.create() ;
}
}
具體來說,該語句位於列表底部:
{
root = HashLifeTreeNode.create() ;
}
看起來像沒有簽名的方法,這是什么意思?
先感謝您!
那是一個實例初始化器 。
這是一些代碼,它在構造函數體執行之前,作為構造新實例的一部分而執行。 但是,直接在方法之后以這種方式進行布局是很奇怪的。 (老實說,很少見到它。在這種情況下,如果在同一個類中聲明了字段,則看起來它應該只是一個字段初始化程序。(尚不清楚您是否向我們展示了整個過程還是沒有。)
實例初始化程序和字段初始化程序按文本順序執行,在超類構造函數之后,在“此”構造函數主體之前。
例如,考慮以下代碼:
class Superclass {
Superclass() {
System.out.println("Superclass ctor");
}
}
class Subclass extends Superclass {
private String x = log("x initializer");
{
System.out.println("instance initializer");
}
private String y = log("y initializer");
Subclass() {
System.out.println("Subclass ctor");
}
private static String log(String message)
{
System.out.println(message);
return message;
}
}
public class Test {
public static void main(String[] args) throws Exception {
Subclass x = new Subclass();
}
}
輸出為:
Superclass ctor
x initializer
instance initializer
y initializer
Subclass ctor
它是一個實例塊 (代碼對),在構造該實例之前將被執行,該實例塊將在您每次嘗試創建HashLifeTreeUniverse實例時執行。
您突出顯示的一對大括號之間的代碼將在調用構造函數之前執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.