假设我有一个类,我希望能够通过传递旧实例和一些新数据来创建新实例。另外我有一个abstract
类,其他类将从该类继承,我希望这个复制行为在抽象类中实现。
这可以用Java完成,如此
evan@vbox ~/junk > cat Test.java
public abstract class Test
{
public String name;
public String data;
/* Standard Constructor */
public Test(String name, String data)
{
this.name = name;
this.data = data;
}
/* "Copy" constructor: old instance data is copied, except this.data*/
public Test(Test oldInst, String newData)
{
/* Copy unchanged data from old instance */
this.name = oldInst.name;
/* Insert new data */
this.data = newData;
}
/* Derived classes will implement this */
public abstract void identify();
}
evan@vbox ~/junk > cat Test_Inh.java
public class Test_Inh extends Test
{
public Test_Inh(String name, String data)
{
super(name, data);
}
public Test_Inh(Test_Inh oldInst, String newData)
{
super(oldInst, newData);
}
public void identify()
{
System.out.println("This is a Test_Inh with properties:\n\tName: "
+ this.name + "\n\tData: " + this.data);
}
}
evan@vbox ~/junk > cat Main.java
public class Main
{
public static void main(String[] args)
{
Test_Inh t1 = new Test_Inh("name", "original data");
t1.identify();
Test_Inh t2 = new Test_Inh(t1, "new data");
t2.identify();
}
}
哪个输出:
evan@vbox ~/junk > javac *.java && java Main
This is a Test_Inh with properties:
Name: name
Data: original data
This is a Test_Inh with properties:
Name: name
Data: new data
我想在Scala中实现此行为,但是不能从子类访问超级构造函数。我的理解是,备用构造函数应由Scala中的伴随对象或工厂处理。但是,在使用抽象类时,这些都没有意义。