Does copy of an object through copy constructor get the same instance variable as the original object?

我的梦境 提交于 2019-12-20 07:30:21

问题


Does a copy of an object with object instance variables get the same instance variable as the original object? if so, I was wondering if the original and copy objects are referencing to the same instance variables.


回答1:


Unlike C++, Java does not provide copy constructors automatically. There is therefore no general answer to any question about the behavior of copy constructors, as Java places no restrictions on their behavior.

Nevertheless, every object, however initialized, has its own instance variables. These are not shared with any other object; they can be "the same" as another object's only in the sense of holding the same value. Variables of primitive type such as int are wholly independent of each other. Any two variables of reference type may hold values that refer to the same object, however, provided that their declared types are both compatible with the class of that object. A copy constructor could easily create such an effect, but in no way does one need to do so.



来源:https://stackoverflow.com/questions/42589007/does-copy-of-an-object-through-copy-constructor-get-the-same-instance-variable-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!