假设我有以下代码
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()调用中。相反,我想简单地传递一个已经存在的对象,并将其用作父类(super class)。
我想做这个...
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?
}
}
最佳答案
您不只是想为您的父类(super class)准备一个copy constructor吗?
public class SuperClass {
protected int super_class_value;
public SuperClass (int value) {
this.super_class_value = value;
}
protected SuperClass (SuperClass super_class) {
this.super_class_value = super_class.supper_class_value;
}
}
public class Subclass extends SuperClass {
protected int subclass_value;
public SubClass(SuperClass super_class, int subclass_value) {
super(super_class);
this.subclass_value = subclass_value;
}
}
另请参见此处关于编写复制ctor的问题:
Does Java have a default copy constructor (like in C++)?
关于java - 我应该如何使用父类(super class)的实例构造子类?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28463340/