C++ vs Java constructors

前端 未结 14 2461
一个人的身影
一个人的身影 2021-02-09 20:31

According to John C. Mitchell - Concepts in programming languages,

[...] Java guarantees that a constructor is called whenever an object is created.

14条回答
  •  无人共我
    2021-02-09 21:27

    There are two cases in Java (I'm not aware of any more) in which a class' may be constructed without its constructor being called, without resulting to hacking in C or similar:

    • During deserialisation, serialisable classes do not have their constructor called. The no-arg constructor of the most derived non-serialisable class is invoked by the serialisation mechanism (in the Sun implementation, through non-verifiable bytecode).
    • When the evil Object.clone is used.

    So the claim that constructors are always called in Java, is false.

提交回复
热议问题