Currently I declare all my static fields like so:
public static final int EXAMPLE_OF_STATIC_FIELD = 0;
Say I have a base class with fields that represent all errors that could ocurre inside the class:
public class Base {
public static final int ERROR_1 = 0;
public static final int ERROR_2 = 1;
public static final int ERROR_3 = 2;
}
If I extend this base class and I would like to add more Error types to the class, I would do the following:
public class OffSpring extends Base {
public static final int NEW_ERROR_1 = 3;
}
For me to declare new Error types, I need to know the value of the Error types from the base class, which (in my opinion) in not very convenient, since I could accidentally declare an Error Type in an offspring class of the Base class with the same value as an Error type from the Base class. For example:
public static final int NEW_ERROR_1 = 0;
which would be the same as
public static final int ERROR_1 = 0;
which would conflict…
I thought of maybe using an Enum Class, however it turns out that you can’t extend it.
Can enums be subclassed to add new elements?
Another option would be to use String value type instead of int value type for all the static fields, but this is not a very efficient solution…
How can I add more fields to an offspring of a class, without them conflicting with the super class?
I would question whether you really want to do this. If the constants are private to their declaring classes, why does it matter if they reuse the same values? If there is a context where it is important that different errors do not use the same values, then that suggests strongly that they should not actually be private.
If you do actually want to do this, you could do something like this:
If you want to have multiple subclasses of
Basewhich each define their own error codes, though, you’re in trouble.