Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Peculiar Java Scope

I'm browsing through the Android source, just kind of reading it, and I've come across a strange chunk of code in Android.Util.JsonReader. It is as follows:

private final List<JsonScope> stack = new ArrayList<JsonScope>();
{
    push(JsonScope.EMPTY_DOCUMENT);
}

What is this doing exactly? That is, the scope immediately following the new assignment? If I understand correctly, whenever this class, JsonReader is instantiated, (not static, right?), stack will be initialized here, rather than via a this.stack = ... in the constructor, correct?

What then does the scope do? Is that executed after stack is initialized? I'm just a bit confused here, as to the name of this pattern, and its use.

like image 461
Josh Avatar asked Apr 16 '12 19:04

Josh


1 Answers

Its not related to the new Statement. It is an initializer, kind of like an unnamed parameterless constructor.

http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.6

They are executed before the constructors of a class in textual order

http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.5

like image 67
Jens Schauder Avatar answered Sep 28 '22 03:09

Jens Schauder