声明后是否可以初始化最终变量?

发布于 2025-01-08 16:43:54 字数 328 浏览 0 评论 0原文

这是否可能,很少有人认为它可能,我也在这里看到它 链接..但是当我亲自尝试时,它给了我编译时错误..

我的意思是这个,

Class A{
    private final String data;

    public A(){
        data = "new string";
    }
}

提前感谢..

Is this even possible, few argue its possible and i saw it here too link.. but when i personally tried it gives me compile time errors..

i mean this,

Class A{
    private final String data;

    public A(){
        data = "new string";
    }
}

Thanks in advance..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

烈酒灼喉 2025-01-15 16:43:54

是的,这是可能的。类是用小写 c 编写的。否则你的代码完全没问题(除了标识):

public class A {
   private final String data;

   public A() {
      data = "new string";
   }
}

Yes, it is possible. Class is written with small case c. Otherwise your code is perfectly fine (except for identation):

public class A {
   private final String data;

   public A() {
      data = "new string";
   }
}
眼角的笑意。 2025-01-15 16:43:54

您可以在声明后初始化最终实例变量。

  • 如果它是静态的,则必须在静态初始化中对其进行初始化
    堵塞。
  • 否则,您必须在构造函数中对其进行初始化。

您发布的代码的问题是大写的C。正如鲍里斯指出的那样,它应该是class

You can initialize a final instance variable after declaration.

  • If it's static, you have to initialize it in a static initialization
    block.
  • Else, you have to initialize it in the constructor.

The problem with the code you've posted is the uppercase C. It should have been class as Boris pointed out.

长安忆 2025-01-15 16:43:54

您可能有多个构造函数,在这种情况下,您必须在每个构造函数中初始化最终实例字段。

It is likely that you are having more than one constructor, in that case you must initialize the final instance field in each of those constructors.

倒带 2025-01-15 16:43:54

就像鲍里斯建议的那样,代码很好。但您不能做的是为最终变量数据分配第二个值。 data = "another string"; 将无法编译,因为 data 是最终的,因此其值在初始化后无法更改。

public class A {
   private final String data;

   public A() {
      data = "new string";
      data = "another string";
   }
}

Like Boris suggested the code is fine. What you can not do though, would be to assign a second value to the final variable data. data = "another string"; will not compile, since data is final and thus its value can not be changed after the initialization.

public class A {
   private final String data;

   public A() {
      data = "new string";
      data = "another string";
   }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文