I try to use a simple example for better undersanding: I’ve got a class Tool and child classes which are extending class Tool: Hammer, Saw. Both have defined some fields like weight and both are overriding method getCost with own implementation.
Tool first_tool = new Hammer();
Tool second_tool = new Saw();
I need a method in Tool class, that will to do a copy of any tool, such way, that first_tool_copy is from the same subclass as first_tool. How can I make this possible? I need something like:
/* Copy tool, change parameters of copy, the original won't change */
/* first_tool_copy will be instance of Hammer class */
first_tool_copy = first_tool.copy
first_tool_copy.weight = 100
Conclusions: I would like to have some simple copy constructor common for all subclasses.
I would make
Toolabstract, and add anabstract copymethod toTool. Then each subclass is forced to provide its own implementation. This is a fairly OO approach, and takes advantage of dynamic dispatch.Otherwise, you’d provide a concrete implementation in
Toolwhich you’d have to update every time to want to handle a new subclass ofTool. This method would have to useinstanceof,getClass(), or similar non-OO techniques to create the right class. Ew.Remember what Effective Java Item 10 tells us: Override
clonejudiciously.Assuming the
Toolimplementation looks something like the below class, you could do this with reflection:I wouldn’t recommend this, though. It’s just smelly and ugly to me.