Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java uninitialised constants in an abstract class

Tags:

java

abstract

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?

like image 229
user3210398 Avatar asked Jan 28 '23 10:01

user3210398


1 Answers

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

like image 198
Gustavo Avatar answered Feb 07 '23 17:02

Gustavo