Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java- Using a constant in an abstract class that needs to be used by subclasses as well

I have an abstract class and 2 subclasses. There are 4 constants that relate to all the classes. I was going to place the finals in the abstract class but I understand a final variable is not inherited? Would I have to define the constant in every class (seems inefficient)? Or just make the constant an instant variable (doesn't sound like a good idea)?

What are ways I can go about this?

like image 520
spaz Avatar asked May 03 '12 16:05

spaz


1 Answers

The following would be available to all of your sub-classes if defined in the abstract class.

public static final Integer MYCONSTANT = 42;

or

static final Integer MYCONSTANT = 42;

or

protected static final Integer MYCONSTANT = 42;

The second one (package-private) is only available to classes within the same package. The third (protected) would be available to all sub-classes irrespective of their package.

like image 93
Martin Avatar answered Sep 30 '22 08:09

Martin