C++ vs Java constructors

前端 未结 14 2455
一个人的身影
一个人的身影 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:10

    Java can actually allocate objects without(!) calling any constructor.

    If you browse the sources of ObjectInputStream you will find that it allocates the deserialized objects without calling any constructor.

    The method which allows you to do so is not part of the public API, it is in a sun.* package. However, please don't tell me it is not part of the language because of that. What you can do with public API is put together the byte stream of a deserialized object, read it in and there you go with an instance of the object whose constructor was never called!

提交回复
热议问题