user2976270
user2976270

Reputation: 105

Copy constructor that copy other object values

This is my Class:

public class City
{
    private String _cityName;
    private Point _cityCenter;
    private Point _centralStation;
    private long _numOfResidents;
    private int _noOfNeighborhoods;
    private final long RESIDENTS_CONST_VALUE = 0;
    private final int NEIGHBORHOODS_CONST_VALUE = 1;
}

One of my constructor is Copy from other object (same object):

public City(City other)
{
    _cityName = other._cityName;
    _cityCenter = other._cityCenter;
    _centralStation = other._centralStation;
    _numOfResidents = other._numOfResidents;
    _noOfNeighborhoods = other._noOfNeighborhoods;      
}

public Point(Point point)
{
    _x = point._x;
    _y = point._y;
}

This constructor get another City object and copy it's values. My question is if what i have done it's OK to avoid aliasing or i need to do something else

Upvotes: 2

Views: 422

Answers (3)

A4L
A4L

Reputation: 17595

What you have done looks sane, at least because you haven't copied the Point objects, those are most likely mutable, i.e. if you copy them by simple assignment you would copy only the reference and changes to one object will reflect in the 'copy' -> shallow copy. If you need to make a copy of them too then you'll have to implement a "copy constructor" for them too.

However the standard way of doing this in java is to implment the Colneable interface and override the clone method.

Upvotes: 0

mavroprovato
mavroprovato

Reputation: 8372

The only problem I see is with the reference to the Point class (I'm assuming that we are taking about java.awt.Point). This class is mutable, so the City class you are copying from can change it, and the change will be reflected in your copy also. Use the following code to copy the Point object:

_cityCenter = new Point(other._cityCenter);
_centralStation= new Point(other._centralStation);

The rest of the fields are either primitives or immutable, so it is OK

Upvotes: 2

Renjith
Renjith

Reputation: 3274

The problem is that you are copying the reference from old object to new.It will create problems while copying mutable fields.If both of the objects share common reference to a field, changing the value in one object will affect copied object as well.

Upvotes: 3

Related Questions