java - 当声明最终实例时为什么我必须初始化它?

标签 java final

对于以下代码,我收到错误变量“类型”可能尚未初始化:

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 表示创建一个常量,即其值不会改变的变量,因此称为 finalGeeksForGeeks有一篇关于这方面的好文章。引用:

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/

相关文章:

java - 公共(public)最终字段的序列化

java - 为最终变量赋值

java - 导入的 java 类中的公共(public)静态最终变量

java - Java SE 6 或 Java SE 7 中是否有非最终字段

Java字符串字符分析

java - 本地化遗留产品?

java - JsonMappingException 没有在应该抛出的时候抛出

java - 如何在 IntelliJ 中快速输入记录器定义?

java - 使用多个数据库模式的 JPA

java - 在ArrayBlockingQueue中,为什么将final成员字段复制到本地final变量中?