Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Copy Constructor concept n Java

 
Reddy Prasad
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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,
Prasad
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64629
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This forum is for questions on JDBC. I've moved this topic to a more appropriate forum: Java in General (beginner).
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Strangely enough, we had a discussion about this just this morning!
 
Jeroen T Wenting
Ranch Hand
Posts: 1847
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hardly strange, a new course period has AFAIK started at many schools...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic