如何处理继承链中的默认值而不写入重复代码?
问题描述:
所以我们可以说我有A类,它是这样定义的:如何处理继承链中的默认值而不写入重复代码?
public class A{
private int x;
public A(){
this(13);
}
public A(int x){
this.x = x;
}
}
然后,我有一个B类需要实现Y,所以是这样的:
public class B extends A{
private int y;
public B(){
}
public B(int x){
this(x, 0);
}
public B(int x, int y){
super(x);
this.y = y;
}
}
我的问题是:我在做什么public B()
?我打电话给super(),以便A分配默认值/做任何事情,然后在该构造函数中执行另一个this.y = y
,或者我打电话给this(13)
?
这两种方法似乎都需要一些不好的做法。一个人在两个地方写this.y = y
。另一个需要我重复默认值,并且每次更改默认值时都需要更改。
答
如果在构造函数的第一行没有调用继承的构造函数,那么将会调用继承类的默认构造函数。如果没有默认的构造函数,那么你将不得不在构造函数的第一行定义它应该使用的超级构造函数。
public class A{
public A(){
}
public A(String text){
}
}
public class B extends A{
public B(){
//having nothing is same as super();
//here you can also call the other constructor
//super(""); is allowed
}
public B(String text){
//having nothing is same as super();
//but if you add a super(text) then you set this instance to super(text); instead
}
}
public class C{
public C(String text){
}
}
public class D extends C{
public D(){
super();// this is incorrect and will not compile
}
public D(String text){
super(text);//this is fine
}
}
希望这对我有所帮助。
答
如果这些字段不是最终的,您可以在声明它们的位置分配默认值。所以代码将如下所示:
class A{
private int x = 13;
public A(){
//use default value for x
}
public A(int x){
this.x = x;
}
}
class B extends A {
private int y = 0;
public B(){
//use default value for x and y
}
public B(int x){
super(x);
//use default value for y
}
public B(int x, int y){
super(x);
this.y = y;
}
}
您不需要做任何事情。 'B()'隐式调用'super()',所以'A()'被调用。 –
但是如果我什么都不做,我仍然需要给y一个默认值,这就是问题所在。我最终不得不这样做,再次,当我已经做到了。 – WinterDev
哦,对。抱歉。没有发现你正在分配'y'。所以,你只需要在'B()'中分配'y'。 –