Class static blocks

# Michael O'Brien (17 years ago)

I wanted to clarify the meaning of a static block. Consider:

class Shape {

static var count
var origin

static {
	//	Is this static initialization code?

	count = 1
}

{

	//	Is this instance initialization code?

	origin = 0		
}

}

Reading the latest draft of the grammar I'm assuming that you must now
put static init code inside a static {} block. Is this correct?

Does that mean that other directives outside of methods and static
blocks are instance initialization code? If so, does it run before or
after the constructor code?

Michael

# Jeff Dyer (17 years ago)

On 4/20/08 11:52 AM, Michael O'Brien wrote:

I wanted to clarify the meaning of a static block. Consider:

class Shape {

static var count var origin

static { // Is this static initialization code?

count = 1 }

{

// Is this instance initialization code?

origin = 0
} }

Reading the latest draft of the grammar I'm assuming that you must now put static init code inside a static {} block. Is this correct?

That is correct.

Does that mean that other directives outside of methods and static blocks are instance initialization code?

No, statements are no longer allowed at the top level of a class definition. Class initialization code goes in 'static {...}' blocks, and instance initialization code goes in constructors, of course. Multiple 'static {...}' blocks are allowed.

# Michael O'Brien (17 years ago)

Jeff,

What happens to "var" declarations inside a static block? Are they converted to static declarations or disallowed?

Similarly, I presume a redundant "static" attribute inside a static
block is allowed.

Michael

# Lars Hansen (17 years ago)

Static blocks are anonymous parameterless functions. "var" hoists to the top of these functions (as in any other functions); "static" is disallowed (because it's legal only on class attributes); and other binding forms that are legal in functions ("function", "let", "const") are legal.