Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Java have a copy constructor?

Why doesn't Java support a copy constructor like in C++?

like image 1000
Cuga Avatar asked May 06 '09 02:05

Cuga


People also ask

Is there a copy constructor in Java?

A copy constructor in a Java class is a constructor that creates an object using another object of the same Java class. That's helpful when we want to copy a complex object that has several fields, or when we want to make a deep copy of an existing object.

Is copy constructor default in Java?

No, it doesn't have a default copy constructor. A default constructor. You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors.

Why is my copy constructor not being called?

It's because of copy elision optimization by the compiler. Adding -fno-elide-constructors option to g++ while compiling will disable that optimization.

What are the disadvantages of copy constructor?

The only disadvantage I can think of to a copy constructor is that some large objects can be expensive to copy (eg. copying a long string involves allocating a large block of memory then copying all the content).


2 Answers

Java does. They're just not called implicitly like they are in C++ and I suspect that's your real question.

Firstly, a copy constructor is nothing more than:

public class Blah {   private int foo;    public Blah() { } // public no-args constructor   public Blah(Blah b) { foo = b.foo; }  // copy constructor } 

Now C++ will implicitly call the copy constructor with a statement like this:

Blah b2 = b1; 

Cloning/copying in that instance simply makes no sense in Java because all b1 and b2 are references and not value objects like they are in C++. In C++ that statement makes a copy of the object's state. In Java it simply copies the reference. The object's state is not copied so implicitly calling the copy constructor makes no sense.

And that's all there is to it really.

like image 101
cletus Avatar answered Sep 19 '22 15:09

cletus


From Bruce Eckel:

Why does [a copy constructor] work in C++ and not Java?

The copy constructor is a fundamental part of C++, since it automatically makes a local copy of an object. Yet the example above proves that it does not work for Java. Why? In Java everything that we manipulate is a handle, while in C++ you can have handle-like entities and you can also pass around the objects directly. That’s what the C++ copy constructor is for: when you want to take an object and pass it in by value, thus duplicating the object. So it works fine in C++, but you should keep in mind that this scheme fails in Java, so don’t use it.

(I recommend reading the entire page -- actually, start here instead.)

like image 27
Dan Breslau Avatar answered Sep 17 '22 15:09

Dan Breslau