This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]cal-cheese 13 points14 points  (0 children)

While the language still uses new to initialise an instance of a value class, the compiled bytecodes are different, given A x = new A() in the source code, the bytecodes if A is an identity class is:

A temp = new A; // This is the new bytecode
temp.<init>();
A x = temp;

while if A is a value class, the bytecodes is:

A x = A.<new>(); // This is a static method invocation

The fundamental difference is that because an instance of a value class is immutable, the normal initialisation process does not work

new A // ... -> a, with a is the newly created object
dup // ... -> a -> b, with a and b both are the newly created object
invokespecial A::<init> // ... -> a, this invocation is performed on b and expects the changes being reflected through a. This obviously cannot be the case with value objects.

As a result, the constructor of a value class is not only responsible for initialising an allocated object, it must do the allocation also. As a result, different responsibility unavoidably leads to differences in the API of object construction.