Search code examples
javastaticfieldfinal

Need to initialize a static final field in the subclasses


I asked a question, but it was very dirty, and a lot of people didn't understand. So, I need to declare a final static field, that is only going to be initialized in the subclasses. I'll show an example:

public class Job {
    public static final String NAME;
}

public class Medic extends Job {

    static {
        NAME = "Medic";
    }
}

public class Gardener extends Job {

    static {
        NAME = "Gardener";
    }
}

Something like this. I know this code is not going to work, since the NAME field in the Job class needs to be initialized. What i want to do is to initialize that field individually in each subclass (Medic, Gardener).


Solution

  • You need this

    public enum Job {
        MEDIC(0),
        GARDENER(1);
    
        /**
         * get identifier value of this enum
         */
        private final byte value;
    
        private Job(byte value) {
            this.value = value;
        }
    
        /**
         * get identifier value of this enum
         * @return <i>int</i>
         */
        public int getValue() {
            return this.value;
        }
    
        /**
         * get enum which have value equals input string value
         * @param value <i>String</i> 
         * @return <i>Job</i>
         */
        public static Job getEnum(String value) {
            try {
                byte b = Byte.parseByte(value);
                for (Job c : Job.values()) {
                    if (c.getValue() == b) {
                        return c;
                    }
                }
                throw new Exception("Job does not exists!");
            } catch (NumberFormatException nfEx) {
                throw new Exception("Job does not exists!");
            }
        }
    
        /**
         * get name of this job
         */
        public String getName() {
            switch (this) {
            case MEDIC:
                return "Medic";
            case GARDENER:
                return "Gardener";
            default:
                throw new NotSupportedException();
            }
        }
    }