1

I have several subclasses of a class "A", say B, C, and D. I store several of these in a generic

ArrayList<A> stuff;

B, C, and D have absolutely no different data members than A. The only way they differ is by different overridden methods. I would LIKE to be able to copy any instance of class A to another instance of class A (while retaining the true subclass)

Something like:

A obj1 = (A)new B(...)
A obj2 = (A)new C(...)
A obj3 = obj1.copy();
// (obj3 instanceof B) == true

Normally this would require B, C, and D to implement custom copy methods. However, this seems like a waste since the data members are exactly the same, and they would only exist so that the class is preserved.

Is there any way I could get away with only implementing copy in class A, and still preserving the underlying classes of the objects?

EDIT:

If I'm thinking correctly, the problem I would run into if just the superclass had a copy method:

class A {
    int dataMember;
    public A copy() {
        A ret = new A(); // !!
        ret.dataMember = dataMember;
        return ret;
    }

}

When calling "new" I couldn't generically determine what subclass of A the class is, and furthermore explicitly instantiate an instance of that. Or is there a way to do this?

1
  • 1
    Why not just give the super class a copy method? Commented Apr 28, 2012 at 2:01

2 Answers 2

1

You could give A a copy constructor:

class A {

    public A(A other) {
        //copy other's fields to this instance
    }
}

Subclasses of A could also expose a constructor that took an A instance and passed it to the super constructor:

class B extends A {

    public B(A other) {
        super(other);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Are you familiar with clone? It will copy all your fields and mantain the derived class. Be careful that it won't do a clone of each field's object, but they will point to the same reference.

public Object clone() {
    try {
        return super.clone(); 
    } catch (CloneNotSupportedException e) {} // Will never happen if your object implements the Cloneable interface
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.