I have an instance of type Base. I want to create a new Derived whose Base portion is initialised from the existing Base instance. Preferably with new copies of the members.
I was going to create a constructor on Derived that accepts a Base and copy all the Base members individually but wondered if there was a better, more maintainable way where I don't need to list all members of Base? If Base gets extended then it'd be nice for the copy to continue to work.
i would advice that get rid of this habit of relating Java and C++, they are two different languages with similar syntaxes thats all. or else you may fall into trouble switching mindsets. using clone() method is a better approach for creating copies of the objects
Joined: Sep 16, 2009
shukla raghav wrote:i would advice that get rid of this habit of relating Java and C++, they are two different languages with similar syntaxes thats all. or else you may fall into trouble switching mindsets.
OK, makes sense.
using clone() method is a better approach for creating copies of the objects
clone() would create me a distinct superclass object. That's not much use if I have inheritance.
I could have avoided inheritance and aggregated the "superclass" portion in the main class. Then I would not inherit the setters and getters.
I disagree with shukla raghav. The clone() method is not helpful there. If you have a superclass copy constructor, you can simply copy all the fields from the old instance to the new one. If the fields are primitives or immutable reference types, there is no need for any further action. If however the fields are mutable (eg List<String>) they might require duplication. There is a method in the Collections class which can copy Lists easily.
You are not changing the state and structure of the classes, but adding a bit to their interface. The fields are the same, and you ahve simply added an overloaded constructor.
And I thought you were a C# chap
Joined: Sep 16, 2009
Maneesh Godbole wrote:"P Uk",
Please check your private messages for an important administrative matter.