Copy constructors in Java

Are copy constructors not used in Java?  I see little or no mention of them in Java books (compared to C++)
omomAsked:
Who is Participating?
 
diakovConnect With a Mentor Commented:
Look at these articles, that extensivelly cover the issue about overriding Object methods (it does relate) and canonical objects:

http://www.javaworld.com/javaworld/jw-10-1998/jw-10-techniques_p.html

http://www.javaworld.com/javaworld/jw-01-1999/jw-01-object-2.html

Look at the bottom of the page for the second one.

Cheers,
  Nik

0
 
heyhey_Commented:
you can use / implement copy constructors in Java

'public String(String value)
Allocates a new string that contains the same sequence of characters as the string argument.'

but it's much more Java'ish to use .clone() method.

0
 
pyxideCommented:
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
Ravindra76Commented:

I think these copy constructors are not needed in java
0
 
diakovCommented:
Well, think again. In a complex application, quite often you need to copy an object, for example if you want to pass the reference to another object that might destroy the contents of the referenced object. And if you do not know the type to cast, you might not even be able to copy it manually if that is what you think you can do.

There also other aspects that make an object cannonical, read the article I suggested.

Cheers,
  Nik
0
 
heyhey_Commented:
>> Well, think again. In a complex application...

what about using .clone() instead of copy constructor ? :)
0
 
omomAuthor Commented:
I will have to agree with heyhey in that java.lang.Object.clone()

From the docs:

Creates a new object of the same class as this object. It then initializes each of the new object's fields by assigning it the same value as the corresponding field in this object. No constructor is called.

The clone method of class Object will only clone an object whose class indicates that it is willing for its instances to be cloned. A class indicates that its instances can be cloned by declaring that it implements the Cloneable interface.

Heyhey please lock
0
 
omomAuthor Commented:
Oops, I tried to reject the answer, but something went wrong.
sorry heyhey
0
 
heyhey_Commented:
no problem.
enjoy Java :)
0
 
diakovCommented:
Well, things go wrong sometimes. I'll make a question for heyhey.

Nik.
0
 
omomAuthor Commented:
thanks,diakov
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.