假设我有以下代码
public class SuperClass {
protected int super_class_value;
public SuperClass (int value) {
this.super_class_value = value;
}
}
public class Subclass extends SuperClass {
protected int subclass_value;
public SubClass(int super_class_value, int subclass_value) {
super(super_class_value);
this.subclass_value = subclass_value;
}
}
但是,现在我希望能够将 SuperClass 对象传递给 SubClass 构造函数。我该怎么做?
public SubClass(SuperClass super_class, int subclass_value) {
//What do I do here?
this.subclass_value = subclass_value;
}
基本上,我想做这样的事情......
public SubClass(SuperClass super_calss, int subclass_value) {
super(super_class.super_class_value);
this.subclass_value = subclass_value;
}
但是如果 SuperClass 更复杂,我不想将每个值都添加到 super() 调用中。相反,我想简单地传入一个已经存在的对象,并将其用作超类。
我想做这个...
public SubClass(SuperClass super_class, int subclass_value) {
super(super_class);
this.subclass_value = subclass_value;
}
但我不确定这是否允许?
如果我将构造函数添加到 SuperClass 定义中,似乎我可以执行上述操作。但那会是什么样子?
public class SuperClass {
protected int super_class_value;
public SuperClass (int value) {
this.super_class_value = value;
}
public SuperClass (SuperClass super_class_object) {
//What is done here?
}
}