• Post Reply Bookmark Topic Watch Topic
  • New Topic

Are there copy constructors in Java like in C++?  RSS feed

 
Timothy Sam
Ranch Hand
Posts: 751
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And again... To satisfy my burning curiosity about their differences... Please explain why there is or there is none... Thanks!
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can write a constructor for a class that takes the same type of class as input in Java - a copy constructor. The only difference with C++ is that Java people usually don't explicitly call this a "copy constructor".
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To add to Jesper's explanation: Java will never automatically generate a copy constructor as the C++ compiler will sometimes do. When a Java object is passed as a method argument, a reference to the object is passed. Java never automatically copies objects, so no implicit copy constructors are needed.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
While a copy constructor is perfectly feasible in Java, a lot of people would use clone() instead. I do tend to use clone(), myself, though I think it's a clunky part of the language.

Regarding things that C++ does implicitly, one of the big differences between C++ and Java is that Java does far fewer things implicitly. Try stepping through a complicated C++ program in a debugger, using Step Into, and see how many implicit method calls there are - it's a lot. All the implicit stuff that C++ does is "clever". But "clever" is not the same as "wise", in software or elsewhere!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!