繁体   English   中英

需要在子类中初始化一个静态的final字段

[英]Need to initialize a static final field in the subclasses

我问了一个问题,但是很脏,很多人不理解。 因此,我需要声明一个最终的静态字段,该字段只会在子类中初始化。 我将举一个例子:

public class Job {
    public static final String NAME;
}

public class Medic extends Job {

    static {
        NAME = "Medic";
    }
}

public class Gardener extends Job {

    static {
        NAME = "Gardener";
    }
}

这样的事情。 我知道此代码将无法正常工作,因为Job类中的NAME字段需要初始化。 我想要做的是在每个子类(Medic,Gardener)中分别初始化该字段。

你需要这个

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();
        }
    }
}

为什么不在基类中声明抽象方法?

public abstract class Job {
   public abstract String getJobName();
}

然后,您可以在每个实现中返回单独的名称:

public class Medic extends Job {
   @Override
   public String getJobName() {
      return "Medic";
   }
}

public class Gardener extends Job {
   @Override
   public String getJobName() {
      return "Gardener";
   }
}

拥有final static场没有多大意义。

你不可以做这个。 静态字段在每个类中只有一个实例被声明。 由于MedicGardener共享相同的Job超类,因此它们也共享相同的NAME静态字段。 因此,您不能分配两次。

您甚至不能在子类中分配一次,因为可能已经加载和初始化Job类,但尚未加载任何子类。 但是,在类初始化之后,所有static final字段都需要初始化。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM