I would like to write an abstract class (or interface) which either
- Forces all implementing classes to provide a field (ideally static) of a particular type and name (maybe by throwing a compile-time error if it’s missing?), or
- Automatically provides such fields in implementing classes.
An example would be:
public abstract class A {
abstract int counter;
}
public class B extends A {
public int getCounter() {
return counter;
}
}
in which case B’s getCounter() method would return a (static or instance) counter specific to the B class, and not a value inherited from A. Is there any way to do this in Java?
There is not really a good way to do that, nor do I believe there should be. You can accomplish the same thing using abstract methods and writing your algorithms in the base class so that they take advantage of the delegated methods.
Perhaps if you provide more details on why you think you need to do this, we can help you craft a more correct solution.
For example: