4

I'm trying to initialize a private final variable in the constructor of my class. 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. 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

This seems pretty dang similar to the examples in the thread I linked to.

Thank you for the help!

7
  • what error does eclipse give? I cut and pasted your example into IntelliJ, and it was happy. Commented Jul 2, 2014 at 16:25
  • It gives the second code block in my post above. I'm using 4.4.0 and Java 7 but the actual error when I run it is this: Exception in thread "main" java.lang.Error: Unresolved compilation problem: The blank final field myString may not have been initialized at package.<init>(A.java:31) at package.Test.main(Test.java:5)initialized Commented Jul 2, 2014 at 16:27
  • As an aside, I would suggest using the convention of upper-case with underscores for naming constants LIKE_THIS. Commented Jul 2, 2014 at 16:29
  • Does it work if you simply call javac on the file? It's a longshot. Commented Jul 2, 2014 at 16:29
  • 2
    @user3780616 I doubt that the code above produces this error. Please provide the full example (your class A does not have a line #31) Commented Jul 2, 2014 at 16:32

1 Answer 1

5

Your code is perfectly valid. This is probably caused by:

  1. Bad IDE settings
  2. Damaged or alternative javac compiler.

Re-download your IDE, you probably want to download the latest version of it and perform a clean install. You can also try to download and install JDK again (preferably latest version).

Just a little tip. In Java, there is a convention that variable visibility modifier comes first. So instead of final private, learn to write private final.

Sign up to request clarification or add additional context in comments.

1 Comment

Reinstalled JDK and Eclipse and everything works. Not sure why, but hey, it works :) Thanks for the help everybody!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.