+ 1

In most cases, we want a copy constructor in object oriented program in java..I actually do not understand why do we use it!!!!

could anyone explain it to me, thanks

5th Mar 2017, 8:50 PM
Rea
Rea - avatar
2 ответов
+ 3
you can think of a constructor as a fuction that you call in your program to create a new object of a specified class. You write your class to DEFINE objects qualities (attributes) and behavior(methods). To CREATE an object of that class you have to call its constructor in your program. My apologies for the awkward reply to all Java purists.
5th Mar 2017, 9:42 PM
seamiki
seamiki - avatar
0
I supposed that you wandered why we should write // code 1 MyObject obj1 = new MyObject(); MyObject obj2 = obj1.clone(); instead of // code 2 MyObject obj1 = new MyObject(); MyObject obj2 = obj1; That's because variables just hold a reference to an object. In code 1, both variables refer to different objects; obj1 -> OBJECT1 obj2 -> OBJECT1 (copied) obj1.clone() creates a new copy of OBJECT1 and obj2 is assigned an address of new one. In code 2, however, both variable refer to the same object; obj1 -> OBJECT1 <- obj2 because obj2 is just assigned the same address stored in obj1. The latter case can be problematic. Modifying obj2 should affects obj1 because they are actually referes the same object. So obj1.getSomething(); obj2.setSomething(something); obj1.getSomething(); both obj1.getSomething may return different values even if you just wanted to change only obj2. This can cause unexpected behaviors (yes, they are so called bugs!).
5th Mar 2017, 10:56 PM
Twelfty
Twelfty - avatar