This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Copy Constructor concept n Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Copy Constructor concept n Java" Watch "Copy Constructor concept n Java" New topic

Copy Constructor concept n Java

Reddy Prasad

Joined: Mar 09, 2006
Posts: 1
Hi Friends,

I had a doubt is there any concept like copy constructor in Java like C++. If it is there, how can it be performed in Java.Please give the reply with example.

Thanks and Regards,

Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Hi, welcome to the ranch!!

Would that look like this?

You can certainly write the code to make the constructor copy the appropriate fields from old to new, but it's not there automatically. I think the only one of these I've used in the wild is the Attributes object in the XML DOM.

oldWidget.clone() might be an alternative. The object must be written to clone properly. The code would look an awful lot like the copy constructor as it copies each field from old to new. Look at the doc for clone() on the Object class.

Either way, if you're writing the copy code it will be your choice whether to make deep copies or not.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63870

This forum is for questions on JDBC. I've moved this topic to a more appropriate forum: Java in General (beginner).

[Asking smart questions] [About Bear] [Books by Bear]
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Strangely enough, we had a discussion about this just this morning!

[Jess in Action][AskingGoodQuestions]
Jeroen T Wenting
Ranch Hand

Joined: Apr 21, 2006
Posts: 1847
hardly strange, a new course period has AFAIK started at many schools...

I agree. Here's the link:
subject: Copy Constructor concept n Java
It's not a secret anymore!