cemulate
cemulate

Reputation: 2333

Java Implementing copy completely from superclass when classes do not differ by data

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?

Upvotes: 1

Views: 2727

Answers (2)

Luciano
Luciano

Reputation: 8582

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
}

Upvotes: 1

Paul Bellora
Paul Bellora

Reputation: 55213

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);
    }
}

Upvotes: 1

Related Questions