开发者

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

"The Java la开发者_开发问答nguage automatically initializes fields of objects, in contrast to local variables of methods that the programmers are responsible for initializing. Given what you know of intra- and inter-procedural data flow analysis, explain why the language designers may have made these design choices."

Its obvious to me that its to prevent a bug. However, what exactly is that bug? Would it be to condense the possible control flow of some given method?

Could someone go into greater detail on this? I'd really appreciate the help.


It's really easy to do intra-procedural data flow, so it's really easy to check whether a field has been initialized and give warnings if it hasn't (one can write a simplistic decidable algorithm, e.g. make sure all branches of an if initialize a variable, and if one branch doesn't, fail, even if the branch is unreachable).

It's really hard to do inter-procedural data flow, so it's really hard to check whether a field of an object has ever been initialized anywhere in the code (you quickly get into undecidable territory for any reasonable approximation).

Thus Java does the former and gives compile-time errors when it detects uninitialized local variables, but doesn't do the latter and initializes an object's fields to their defaults.


It is not always the case that they are initialized. Objects can be instantiated without invoking any constructor by using reflections in combination with the class sun.misc.Unsafe or ObjectInputStream to access these classes private native methods or directly through JNI. These are intended for the purpose of object serialization/deserialization, and expect the fields to be populated by the deserializer. As for why the designers would have chosen to eliminate direct access to these methods(ie. without reflections) it stands to reason that pointers still left in memory could be used for stack-smashing or return-to-lib-c attacks. Clearing memory allocated for these "automatically" for most programs reduces the security risk as well as reducing the chance for errors. Also note that an attempt to read a local variable that has not been initialized results in a compile error for much the same reason

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜