This week's book giveaway is in the OCP forum.
We're giving away four copies of OCP Java SE 8 Programmer II Exam Study Guide and have Kathy Sierra, Bert Bates, & Elizabeth Robson on-line!
See this thread for details.
Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
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!
 
Java Cowboy
Sheriff
Posts: 16083
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".
 
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.
 
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!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!