Unfortunately I haven't coded Java for about five years and I absolutely can not remember how or why the following code is working.
I stumbled across a similar example and broke it down to this. The emphasis is on the part below the comment: I don't get the constructor notation followed by the block in double brackets. And unfortunately I can not find anything in the Java documentation or by using Google (what word(s) should I google?).
package syntaxtest;
public class Main {
public static void main(String[] args) {
// What kind of notation is this?
MyTest tester = new MyTest() {{
setName("John Johnson");
}};
System.out.println(tester.getName());
}
}
class MyTest {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
So here are my questions:
I guess/ hope I will be able to answer the second question by myself if somebody can provide me with the answer to the first question.
To make it clear: I know the output is John Johnson
;) But I don't know why it is working.
Double brace initialisation creates an anonymous class derived from the specified class (the outer braces), and provides an initialiser block within that class (the inner braces). e.g. new ArrayList<Integer>() {{ add(1); add(2); }};
Java Double Brace Initialization is used to combine the creation and initialization in a single statement. Using double brace initialization, we can initialize collections.
A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created.
No. It is not possible.
This is known as double brace initialization:
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://java.sun.com/docs/books/jls/third_edition/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.
This only works only for non-final classes because it creates an anonymous subclass.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With