对于以下代码,我收到错误变量“类型”可能尚未初始化:
public class Ingredient {
private final String id;
private final String name;
private final Type type;
public static enum Type {
WRAP, PROTEIN, VEGGIES, CHEESE, SAUCE
}
...
}
谁能解释一下为什么吗?
最佳答案
final
表示创建一个常量,即其值不会改变的变量,因此称为 final
。
GeeksForGeeks有一篇关于这方面的好文章。引用:
When a variable is declared with final keyword, its value can’t be modified, essentially, a constant. This also means that you must initialize a final variable. If the final variable is a reference, this means that the variable cannot be re-bound to reference another object, but internal state of the object pointed by that reference variable can be changed i.e. you can add or remove elements from final array or final collection. It is good practice to represent final variables in all uppercase, using underscore to separate words.
如果您不初始化 final
变量,那么拥有它根本没有意义,因为您将无法从非初始化状态更改它。
关于java - 当声明最终实例时为什么我必须初始化它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60047807/