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.
refisn’t the name of a class; it’s the name of the parameter to the second constructor. So themainmethod would actually look like this:Note that objects don’t have names – variables do. Here the value of the
foovariable becomes the value of therefparameter in the second constructor, when that constructor is invoked in the last line above. Also note that the values offoo,barandrefaren’t objects… they’re references to objects.