copy constructors ?? what are they ?

Recommended Answers

All 5 Replies

Member Avatar for coil

Copy constructors exist only in C++. Basically, they allow you to copy an existing object.

To do this in Java, you would need getter methods.

e.g. Birthday b=new Birthday(1, 1, 2010);
Birthday b2=new Birthday(b.getM(), b.getD(), b.getY()); <- effectively copies the "b" object

why you've written get

Or you could use the clone() method to make a copy of an object.

Member Avatar for coil

I used the get method because basically what you're doing is making an object with the same properties as the original.

If you just did this:
Birthday b2=b1;

You wouldn't actually be making a new object, but making a reference to it.

A problem with using a constructor to make a "copy" of an instance of a class is that there could be other methods that had been called that have changed the contents of the class. Using the class's constructor wouldn't get these changes.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.