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.
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.
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.
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.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With