Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to force classes to have public static final field in Java?

Is there a way to force classes in Java to have public static final field (through interface or abstract class)? Or at least just a public field?

I need to make sure somehow that a group of classes have

public static final String TYPE = "...";

in them.

like image 478
serg Avatar asked Mar 17 '10 16:03

serg


People also ask

What is public static final in Java?

A public static final variable is a compile-time constant, but a public final is just a final variable, i.e. you cannot reassign value to it but it's not a compile-time constant. This may look puzzling, but the actual difference allows how the compiler treats those two variables.

How do you initialize a static final variable?

The only way to initialize static final variables other than the declaration statement is Static block. A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.

Can constructor initialize static final variable?

If you declare a static variable in a class, if you haven't initialized it, just like with instance variables compiler initializes these with default values in the default constructor. Yes, you can also initialize these values using the constructor.

Why we use public static final in Java?

public makes it accessible across other classes. static makes it uniform value across all the class instances. final makes it non-modifiable value. So basically it's a "constant" value which is same across all the class instances and which cannot be modified.


2 Answers

No, you can't.

You can only force them to have a non-static getter method, which would return the appropriate value for each subclass:

public abstract String getType();

If you need to map each subclass of something to a value, without the need to instantiate it, you can create a public static Map<Class<?>, String> types; somewhere, populate it statically with all the classes and their types, and obtain the type by calling TypesHolder.types.get(SomeClass.class)

like image 168
Bozho Avatar answered Oct 13 '22 11:10

Bozho


You can define an interface like this:

interface X {
   public static final String TYPE = "...";
}

and you can make classes implement that interface which will then have that field with the same value declared in the interface. Note that this practice is called the Constant interface anti-pattern.

If you want classes to have different values then you can define a function in the interface like this:

interface X {
   public String getType();
}

and implementing classes will have to implement the function which can return different values as needed.

Note: This works similarly with abstract classes as well.

like image 45
Kannan Ekanath Avatar answered Oct 13 '22 11:10

Kannan Ekanath