Question

I am writing a copy constructor for cloning an object. When a class has a refernce to an object which is further inhertited by few other classes.

class Person
{
    String name;
    Address address;
 }

class HomeAdress extends Address
{
}
class OfficeAdress extends Address
{
}

Now in copy constructor for Person, to decide which Address object is to be instiated I have to use instanceof.

public Person(Person p)
{
    name = p.name;
    if(p.address instanceof HomeAddress)
    {
        address = new HomeAddress((HomeAddress) address);
    }else if(p.address instanceof OfficeAddress)
    {
        address = new OfficeAddress((OfficeAddress) address);
    }
}

So the basic problem with this as when new type of address is added to the model. I will have to add a check for the same in Person copy constructor. Is there way to avoid instanceof check to instantiate correct address object. Can I use refelction to avoid instanceof from the code?

Was it helpful?

Solution 2

First, I guess it is a typo:

address = new HomeAddress((HomeAddress) p.address);

Second, instead of casting the object, you can define a copy() method in Address class, (could be) abstract:

abstract class Address {
    abstract Address copy ();
}

And you implement the method in each of the subclasses of Address, then you can call it in the constructor of Person:

public Person(Person p)
{
    name = new String(p.name);
    address = p.address.copy();
}

OTHER TIPS

You should delegate the responsibility for copying the address to the Address class. Whether you implement Cloneable or not, put a clone() method in Address, and then you can (if you need custom handling) override it in each specific Address subclass. Then in your Person copy constructor you just need:

this.address = p.address.clone();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top