简体   繁体   English

在构造函数中初始化final变量

[英]Initialize final variable in constructor

I'm trying to initialize a private final variable in the constructor of my class. 我正在尝试在我的类的构造函数中初始化一个private final变量。 I found this thread explaining how to do it ( Initialize a static final field in the constructor ), but eclipse doesn't seem to like my code. 我发现这个线程解释了如何做( 在构造函数中初始化一个静态的最终字段 ),但是eclipse似乎不喜欢我的代码。 I was wondering if someone could shed some light on what I might be doing wrong. 我想知道是否有人可以说明我可能做错了什么。

public class A {
  final private String myString;

  public A() {
    myString = "content";
  }
}

With this code I'm getting: 使用此代码我得到:

The blank final field myString may not have been initialized 空白的最终字段myString可能尚未初始化

This seems pretty dang similar to the examples in the thread I linked to. 这似乎与我链接的线程中的示例类似。

Thank you for the help! 感谢您的帮助!

Your code is perfectly valid. 您的代码完全有效。 This is probably caused by: 这可能是由于:

  1. Bad IDE settings 糟糕的IDE设置
  2. Damaged or alternative javac compiler. 损坏或替代的javac编译器。

Re-download your IDE, you probably want to download the latest version of it and perform a clean install. 重新下载IDE,您可能想要下载它的最新版本并执行全新安装。 You can also try to download and install JDK again (preferably latest version). 您也可以尝试再次下载和安装JDK(最好是最新版本)。

Just a little tip. 只是一个小小的提示。 In Java, there is a convention that variable visibility modifier comes first. 在Java中,存在一种变量可见性修饰符首先出现的约定。 So instead of final private, learn to write private final. 因此,而不是最终私人,学会写私人决赛。

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

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