For what specific reason does the Java language automatically initialize object fields?

"The Java language automatically initializes object fields, unlike the local variable methods that programmers carry for initialization. Given what you know about flow analysis inside and between procedures, explain why language designers may have made these design options."

It is obvious to me that this is to prevent a mistake. However, what is this mistake? Would it be possible to condense a possible control flow by some given method?

Can anyone elaborate on this in more detail? I am very grateful for the help.

+7
source share
2 answers

It is very easy to make an in-process data stream, so it’s very easy to check if a field has been initialized and give warnings if it does not (you can write a simplified decidable algorithm, for example, make sure that all if branches initialize the variable, and if one branch does not work, do not succeeds even if the branch is unavailable).

It is very difficult to perform interprocedural data flow, so it is very difficult to check whether the field of an object has ever been initialized anywhere (you quickly fall into an unsolvable territory for any reasonable approximation).

Thus, Java does the first and gives compile-time errors when it detects uninitialized local variables, but does not do the latter and initializes the object fields by default.

+3
source

They are not always initialized. Objects can be created without calling any constructor, using reflexes in combination with the sun.misc.Unsafe or ObjectInputStream class to access these classes of private methods or directly through the JNI. They are designed to serialize / deserialize objects and expect the fields to be populated by the deserializer. As to why designers would prefer to exclude direct access to these methods (i.e., without reflections), it is reasonable that pointers left in memory can be used to attack with a break by glass or with a return to lib-c. Clearing the memory allocated for these "automatically" for most programs reduces the security risk and also reduces the likelihood of errors. Also note that trying to read a local variable that has not been initialized results in a compilation error for the same reason.

+1
source

All Articles