我从来没有学过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() ;
}
}
Run Code Online (Sandbox Code Playgroud)
具体来说,这个声明在列表的底部:
{
root = HashLifeTreeNode.create() ;
}
Run Code Online (Sandbox Code Playgroud)
它看起来像一个没有签名的方法,它是什么意思?
先感谢您!
那是一个实例初始化器.
这是在构造函数体执行之前作为构造新实例的一部分执行的一些代码.以这种方式布置它是很奇怪的,直接在一个方法之后.(说实话,这是相对罕见的.说实话.在这种情况下,如果字段在同一个类中声明,它看起来应该只是一个字段初始化器.(目前尚不清楚你是否向我们展示了整个班级与否.)
实例初始值设定项和字段初始值设定项以文本顺序,超类构造函数之后和"this"构造函数体之前执行.
例如,考虑以下代码:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
Superclass ctor
x initializer
instance initializer
y initializer
Subclass ctor
Run Code Online (Sandbox Code Playgroud)