Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining Copy Constructor in Java

This is my class:

class Cat {
    static int lives = 9;
    private String name;
    private int age;
    public Cat(String s, int i) {
        name = s;
        age = i;
    }
    public Cat(Cat c) {
       // Failed attempt to define Copy Constructor
        return new Cat(c.name,c.age);
    }
    public String toString() {
        return (name + ", " + age);
    }
}

I wanted to define the copy constructor so that I could instantiate a new object of Cat from an existing one. Like this:

Cat Garfield = new Cat("Garfield",10);
Cat Tom = new Cat(Garfield);

When I try it out, it gives me compilation error with the copy constructor definition. Please help me understand what's wrong. Yes, the constructor can't have return types and yet we are returning a reference to Cat here.

like image 809
Southee Avatar asked Jan 28 '26 03:01

Southee


2 Answers

Don't do

return new Cat(c. ...

but

this(c.name, ...)

Constructors don't return objects via return!

like image 184
GhostCat Avatar answered Jan 30 '26 15:01

GhostCat


A constructor does not return anything. In a constructor, you are given the "skeleton" of your new object (the reference this), and you initialize it properly as you see fit.

So the first step is to call the proper constructor using that reference, to initialize basic things:

this( c.name, c.age );

And then, since this is a copy constructor, and supposedly you want to get a complete copy of the original Cat, you should proceed to initialize the rest of the fields if you have any.

For example, if you had a field int remainingLives which in your normal constructor was initialized to lives, but the other Cat already lost three lives, then you would have to follow the call to the constructor by

remainingLives = c.remainingLives;

Otherwise it would not be a true copy.

like image 36
RealSkeptic Avatar answered Jan 30 '26 16:01

RealSkeptic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!