[英]Setting value to abstract private field from subclass
I would like to know about the most efficient way to set a value to an abstract private field from a subclass.我想知道从子类为抽象私有字段设置值的最有效方法。 So, for example, have a field called
itemCost
, then I would like to initialize its value to 200 in the subclass.因此,例如,有一个名为
itemCost
的字段,那么我想在子类中将其值初始化为 200。
There is no such abstract private field in Java. Java中没有这样的抽象私有字段。 Only classes and methods can be abstract.
只有类和方法可以是抽象的。 But to emulate an abstract field, I believe there are at least two good methods:
但是要模拟一个抽象的领域,我相信至少有两种好的方法:
final field
in the superclass.final field
。 And initialize it in the child class.abstract setter
for the field to force the subclass to implement/redefine this method and do the specific initializations.abstract setter
,强制子类实现/重新定义该方法并进行具体的初始化。 This is more suitable for varying field content but there is no guarantee that the field will be correctly initialized by all subclasses.abstract class MySuperClass {
final int itemCost;
protected MySuperClass(int _itemCost) {
this.itemCost = _itemCost;
}
}
class MySubClass extends MySuperClass {
public MySubClass() {
super(200);
}
public MySubClass(int itemCost) {
super(itemCost);
}
}
If you do not call super(itemCost)
you will get a compiler error.如果你不调用
super(itemCost)
你会得到一个编译器错误。 So this is very enforcing.所以这是非常强制的。
abstract class MySuperClass {
int itemCost;
protected MySuperClass() { }
abstract void setItemCost();
abstract void setItemCost(int _itemCost);
}
class MySubClass extends MySuperClass {
public MySubClass() {
setItemCost();
}
public MySubClass(int itemCost) {
setItemCost(itemCost);
}
@Override
final void setItemCost() {
this.itemCost = 200;
}
@Override
final void setItemCost(int _itemCost) {
this.itemCost = _itemCost;
}
}
If you are interested in modifying the value after instantiation and if the child class is correctly implemented, then it is a fine solution.如果您有兴趣在实例化后修改值,并且子 class 正确实现,那么这是一个很好的解决方案。 But it is a more verbose, less intuitive and error-prone solution.
但它是一种更冗长、更不直观且容易出错的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.