我尝试使用一个简单的例子来更好地解析:我有一个类Tool和子类,它们正在扩展类Tool:Hammer, Saw. 两者都定义了一些字段,weight并且两者都是getCost自己实现的重写方法.
Tool first_tool = new Hammer();
Tool second_tool = new Saw();
Run Code Online (Sandbox Code Playgroud)
我需要一个Tool类中的方法,它将执行任何工具的副本,这种方式first_tool_copy来自同一个子类first_tool.我怎样才能做到这一点?我需要这样的东西:
/* 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
Run Code Online (Sandbox Code Playgroud)
结论:我想为所有子类提供一些简单的复制构造函数.