Suppose we have an abstract class A, and we want to force all subclasses to have a specific field. This is not possible in Java because we cannot define abstract fields.
Workaround 1: Force subclasses to implement a method that provides the desired value.
abstract class A {
abstract int getA();
}
Disadvantage: each subclass must implement a method for each abstract field that we want to have. This can lead to many method implementations.
Advantage: we can use the method getAin an abstract class and implement methods with it in Awithout their implementation in each subclass. But the value of the method cannot be overwritten by an abstract class.
Workaround 2: Simulate an abstract field, forcing a subclass to give the abstract class a value.
abstract class A {
int a;
public A(int a) {
this.a = a;
}
}
Disadvantage: when we have several fields (> 10), calling the super constructor will look a little ugly and confusing.
Advantage: we can use the field Ain an abstract class and implement methods with it in Awithout implementing them in each subclass. In addition, the value Acan be overwritten by an abstract class.
Question: What workaround is a common way to achieve a goal? Maybe better than higher?
source
share