如何解决Java中缺少抽象字段的问题? [英] How to get around the lack of abstract fields in Java?
问题描述
假设我们有一个抽象类 A
,我们想强制所有子类都有一个特定的字段。这在Java中是不可能的,因为我们无法定义抽象字段。
Assume, we have an abstract class A
and we want to force all subclasses to have a certain field. This is not possible in Java, because we can not define abstract fields.
解决方法1:强制子类实现提供所需的方法值。
Workaround 1: Force subclasses to implement a method which delivers the wanted value.
abstract class A {
abstract int getA();
}
缺点:每个子类都必须实现一个方法对于我们想要的每个抽象字段。这可以导致许多方法实现。
Drawback: Each subclass has to implement a method for each abstract field we want to have. This can lead to many method implementations.
Advantage :我们可以使用方法 getA
在抽象类中实现方法,并在 A
中实现它们,而不在每个子类中实现它们。但是方法背后的价值不能被抽象类覆盖。
Advantage: We can use the method getA
in the abstract class and implement methods with it in A
without implementing them in each subclass. But the value behind the method can not be overwritten by the abstract class.
解决方法2:通过强制子类给出来模拟抽象字段抽象类一个值。
Workaround 2: Simulate the abstract field by forcing the subclass to give the abstract class a value.
abstract class A {
int a;
public A(int a) {
this.a = a;
}
}
缺点:当我们有多个字段(> 10),超级构造函数调用看起来有点难看和混乱。
Drawback: When we have multiple fields (> 10), the super constructor call will look a bit ugly and confusing.
Advantage :我们可以使用字段<抽象类中的code> a ,并在 A
中实现方法,而不在每个子类中实现它们。另外,值 a
可以被抽象类覆盖。
Advantage: We can use the field a
in the abstract class and implement methods with it in A
without implementing them in each subclass. Plus, the value a
can be overwritten by the abstract class.
问题:哪种解决方法是实现目标的常用方法?也许有一个比上面的更好?
Question: Which workaround is the common way to reach the goal ? Maybe there is a better one than the above ones ?
推荐答案
抽象方法可能是最面向对象的。
The abstract method is probably the most object oriented.
如果你有太多的字段,你可能想要重新组合POJO(如果一个新的概念是合适的)。
If you have too many fields, you may want to regroup those in a POJO (if a new concept is appropriate).
这篇关于如何解决Java中缺少抽象字段的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!