Java在子类构造函数中初始化基类字段 [英] java initialize base class fields in subclass constructor
问题描述
这是有关Java子类的一个非常基本的问题,我仍然不明白...
This is a very basic question about subclasses in java, I still don't get it...
假设我有一个具有三个字段且仅具有默认构造函数的超类:
Suppose I have a superclass with three fields and with only the default constructor:
public class Superclass {
public int a;
public int b;
public int c;
}
,我想添加一个字段x.我不能更改 Superclass
,所以我创建了一个子类:
and I want to add a field x. I cannot change Superclass
, so I make a subclass:
public class Subclass extends Superclass {
public int x;
public Subclass(Superclass s) {
super();
// what to do??
}
}
我现在想从现有的 Superclass
对象生成一个 Subclass
对象:
I now want to generate a Subclass
object from an existing Superclass
object:
Superclass s = new Superclass();
s.a = "a";
s.b = "b";
Subclass sc = new Subclass(s);
sc.x = "x";
这样我仍然可以访问 sc.a
, sc.b
等.
such that I can still access sc.a
, sc.b
etc.
如何最好地做到这一点,而不必在子类的构造函数中手动分配所有这些字段?
How can I best do this without assigning all these fields 'by hand' in the constructor of the subclass?
推荐答案
您必须在基类构造函数或子类中为变量分配一个值.
You have to assign a value to the variables either in the base-class constructor or in the child class.
您可以在子类中声明参数化的构造函数,以将值分配给超类中的变量
You can declare a parameterized constructor in sub-class to assign the value to a variable in the superclass
class Subclass extends Superclass {
public int x;
public Subclass(int a,int b, int c,int x) {
super();
this.x = x;
this.a=a;
this.b=b;
this.c=c;
}
}
或者您可以在BaseClass和子类中声明参数化的构造函数,而不是调用 super()
,而是调用经过参数化的构造函数 super(a,b,c)
Or you can declare a parameterized constructor in BaseClass, and in child class, instead of calling super()
, call that parametrized constructorsuper(a,b,c)
class Superclass {
public int a;
public int b;
public int c;
public Superclass(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
}
class Subclass extends Superclass {
public int x;
public Subclass(int a,int b, int c,int x) {
super(a,b,c);
this.x = x;
}
}
这篇关于Java在子类构造函数中初始化基类字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!