user3210398
user3210398

Reputation: 45

Java uninitialised constants in an abstract class

I am writing an abstract class. The classes that extend this class will always use the constant A_CONSTANT, but the value of A_CONSTANT is different for each subclass. The subclasses will also implement the method useConstant. This implementation will be the same for each subclass, other than the value of A_CONSTANT will be different. Preferably I would like to implement useConstant in the abstract class, but an error is produced because A_CONSTANT has not been initialised in the abstract class.

public abstract class AbstractClass {

   public static final int A_CONSTANT;

   public void useConstant(int value) {
      if (value > A_CONSTANT)
         // do something
   }

}

Is there any way around this, or will I have to provide the implementation of useConstant in each of the subclasses?

Upvotes: 4

Views: 84

Answers (1)

Gustavo Pagani
Gustavo Pagani

Reputation: 6988

You can have an abstract method getConstant, then all the subclasses will have to implement it

Upvotes: 8

Related Questions