[Soot-list] constructors with field defaults?

Rhodes H. F. Brown rhodesb at cs.uvic.ca
Tue Apr 11 22:38:05 EDT 2006


Chris makes a good point:

> Eric is basically right, but I want to clarify.  The VM  
> specification says
> that all fields are initialized to 0 when the object is allocated:
>
> http://java.sun.com/docs/books/vmspec/2nd-edition/html/ 
> Concepts.doc.html#15858
>
> Any writes that happen in the constructor happen after the default  
> values
> have already been assigned.

The tricky issue is if you have a final instance field. In this case,  
you can only initialize the field once and (I believe) the verifier  
enforces this. Thus you could get problems if you insert an extra,  
artificial initialization. Furthermore, through some twisted  
inheritance tricks, it is possible for a parent type to access fields  
in a child *before* the child's constructor executes. Hence, you  
still need to rely on the "default" initialization in some cases. For  
example:

class Parent {
	Parent() {
		touch();
	}
	abstract void touch();
}

class Child extends Parent {
	private final int x;
	Child() {
		// must execute super() first...
		x = 1;
	}
	void touch() {
		System.out.println(x); // 0 or 1?
	}
}


-Rhodes


More information about the Soot-list mailing list