问题描述
假设,我们有一个抽象类 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.
优点:我们可以在抽象类中使用方法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.
优点:我们可以在抽象类中使用字段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 中缺少抽象字段的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!