I've never learned Java, but I need to understand what the following piece of code means, the main question is the curly braces:
/**
* 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() ;
}
}
Specifically this statement in the bottom of the listing:
{
root = HashLifeTreeNode.create() ;
}
It looks like a method without a signature, what does it mean?
Thank you in advance!
That's an instance initializer.
It's a bit of code which is executed as part of constructing a new instance, before the constructor body is executed. It's odd to have it laid out in that way though, directly after a method. (It's relatively rare to see it at all, to be honest. In this case it looks like it should just be a field initializer, if the field is declared in the same class. (It's not clear whether you've shown us the whole of the class or not.)
The instance initializers and field initializers are executed in textual order, after the superclass constructor, and before "this" constructor body.
For example, consider this code:
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();
}
}
The output is:
Superclass ctor
x initializer
instance initializer
y initializer
Subclass ctor
See more on this question at Stackoverflow