Reputation: 579
I hope you will help me understand this Copy Constructor
I took more then 2 hours reading reading on websites and I didn't understand anything about it.
I know that a copy constructor is used to copy an object of a class. But I don't understand the code of the copy consturctor.
For Example:
public class Rectangle
{
private double length = 10.0;
private double width = 10.0;
public Rectangle(double length, double width){
this.length = length;
this.width = width;
}
//this is the copy constructor what exactly the argument here? is it the object ref it self? please explain what happening here. and the use
public Rectangle(Rectangle ref){
this.length = ref.length;
this.width = ref.width;
}
this is what I see all the time. but I don't understand the code at all!
ref
is it going to be created in the main program?
let say this is the main program
public class rectangleTest{
public static void main(String[] args){
//is this new_ref object going to be created here?
Rectangle new_ref = new Rectangle(10.0 , 10.0);
This thing will not 100% clear to me unless if someone make a small class and main class showing me what's happening
Thank you.
Upvotes: 1
Views: 1376
Reputation: 4885
The names don't matter. The name just refers to an object, so when you pass it into a method it just used a different name.
Upvotes: 0
Reputation: 32429
You can use your "copy constructor" like this
Rectangle a = new Rectangle (3.0, 4.0);
Rectangle b = new Rectangle (a);
NOTA BENE: Unlike in C++ where a copy ctor is part of the language and called implicitely, the following example in Java will NOT call your copy ctor, but just assign the reference.
Rectangle a = new Rectangle (3.0, 4.0);
Rectangle b = a;
In your case, I would prefer to implement a clone method.
Upvotes: 2
Reputation: 1556
It's more like a clone()
, it duplicates your object so that you have two different instances but which are equal.
Upvotes: 0
Reputation: 1500525
ref
isn't the name of a class; it's the name of the parameter to the second constructor. So the main
method would actually look like this:
Rectangle foo = new Rectangle(10.0 , 10.0);
// Create another Rectangle with the same width and height
Rectangle bar = new Rectangle(foo);
Note that objects don't have names - variables do. Here the value of the foo
variable becomes the value of the ref
parameter in the second constructor, when that constructor is invoked in the last line above. Also note that the values of foo
, bar
and ref
aren't objects... they're references to objects.
Upvotes: 3