本文介绍了java类的最终字段是否应该是静态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在网上找不到任何有关此内容的参考资料。但只是想知道一个类中的最终字段是否应始终为 static
,还是只是一个约定。基于我对它们的用途的理解,我觉得这比用语言强加的东西更合乎逻辑。
I could not find any references online about this. But just wanted to know if final fields in a class should always be static
or is it just a convention. Based on my understanding of their uses, I feel that it is more of a logical thing to do than something that is imposed by the language.
推荐答案
当然不是。如果它们属于类,则它们必须是静态的,如果它们属于类的实例,则它们不是静态的:
Of course not. They must be static if they belong to the class, and not be static if they belong to the instance of the class:
public class ImmutablePerson {
private static final int MAX_LAST_NAME_LENGTH = 255; // belongs to the type
private final String firstName; // belongs to the instance
private final String lastName; // belongs to the instance
public ImmutablePerson(String firstName, String lastName) {
if (lastName.length() > MAX_LAST_NAME_LENGTH) {
throw new IllegalArgumentException("last name too large");
}
this.firstName = firstName;
this.lastName = lastName;
}
// getters omitted for brevity
}
这篇关于java类的最终字段是否应该是静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!