Hi,
any one please tell me why copy constructor in java and use.
Thanks
Regards
Kundan ranjan
software engineer
at HCL
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
Hi,
any one please tell me why copy constructor in java and use.
Thanks
Regards
Kundan ranjan
software engineer
at HCL
Java does(ish). They're just not called implicitly like they are in C++
and I suspect that's your real question.
Firstly, a copy constructor is nothing more than:
public class Blah { private int foo; public Blah() { } // public no-args constructor public Blah(Blah b) { foo = b.foo; } // copy constructor }
Now C++ will implicitly call the copy constructor with a statement like this:
Blah b2 = b1;
Cloning/copying in that instance simply makes no sense in Java because
all b1 and b2 are references and not value objects like they are in C++.
In C++ that statement makes a copy of the object's state. In Java it
simply copies the reference. The object's state is not copied so implicitly
calling the copy constructor makes no sense.
And that's all there is to it really.
Wishes Ada xx
[code]
If to Err is human - then programmers are most human of us all.
"The Analytical Engine offers a new, a vast, and a powerful language . . .
for the purposes of mankind."
— Augusta Ada Byron, Lady Lovelace (1851)
Google 'java copy constructor' for several good (and probably several not-so-good) articles on the use of copy/clone constructors in Java. I don't share Ada's position that they "make no sense" in Java.
In the future, Google first, then ask follow-up questions, referencing with links any of the search results you have questions about.