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?