To answer your question in the title "What is the best practice of inheriting constants in Java?", my answer is: do not inherit them at all.
Inheritance has a special meaning and purpose in object oriented programming, and using inheritance just for convenience because you want to be able to access constants in a particular set of classes does not correspond to this meaning and purpose.
If you have constants that you want to be able to use in different classes, you can put the constants in a separate class. Make this class final
and make the constructor private
so that it can't be subclassed and instantiated:
package com.example;
public final class Constants {
public static final long LONG_ID = 1L;
public static final String STRING_ID = "example_id";
// Private constructor, this class should not be instantiated
private Constants() {
}
}
Then, in a class where you want to use the constants, use import static
:
import static com.example.Constants.LONG_ID;
public class Example {
public void someMethod() {
// Use the constant
long id = LONG_ID;
System.out.println(id);
}
}
The advantage is that the class Example
does not need to extend class Constants
or implement an interface, so you do not need to misuse inheritance, while you still have the same convenience of being able to use the constants with concise syntax.