JAVA - How to copy attributes of an object to another object having the same attributes?

Viewed 16505

Let's say we have an Object A defined like this:

public class ObjectA {
    private Attribute a1;
    private Attribute a2;
    private Attribute a3;
}

For some reason, I need to create a second object B with only the first two attriutes of the Object A :

public class ObjectB {
    private Attribute a1;
    private Attribute a2;
}

So my question is: what is the best approach to copy an Object A to an Object B ? I've been copying the attributes by getters and setters one by one but something tells me there must be a better way to do this ! Especially when the object will have a lot of attributes, I have to write lines and lines of code just to copy all of them to the second Object B ...

Thanks a lot :)

EDIT: I've been being alerted by a "possible duplicate of another question" : How do I copy an object in Java?

My question is slightly different in a way that I'm dealing with 2 different objects who just share the same attributes but not totally !

3 Answers
Related