Reputation: 3581
I was able to do some experiment using the Java language and surprisingly I came up using this lines of code {{ }}
. More over I've noticed using that code structure, I can use any method of the class without creating an object variable for it.
For example:
class Sample {
public void hello() {
// Do something here.
}
}
class SampleTest {
public void testHello() {
new Sample {{ hello(); }};
}
// PSVM ...
}
The question is what is the concept/term called for the statement of line 8?
Upvotes: 1
Views: 252
Reputation: 164
The first brace creates a new AnonymousInnerClass, the second declares an instance initializer block that is run when the anonymous inner class is instantiated. This type of initializer block is formally called an "instance initializer", because it is declared within the instance scope of the class -- "static initializers" are a related concept where the keyword static is placed before the brace that starts the block, and which is executed at the class level as soon as the classloader completes loading the class (specified at http://docs.oracle.com/javase/specs/jls/se5.0/html/classes.html#8.6) The initializer block can use any methods, fields and final variables available in the containing scope, but one has to be wary of the fact that initializers are run before constructors (but not before superclass constructors).
If you want some examples look here: http://c2.com/cgi/wiki?DoubleBraceInitialization
Sarajog
Upvotes: 7