5

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..

Community
  • 1
  • 1
ngesh
  • 13,398
  • 4
  • 44
  • 60
  • 1
    What is the compile time error that you are getting ? – Rocky Feb 25 '12 at 09:03
  • Maybe your compile time error relates to upper-case 'Class'. The rest is perfectly fine and must compile. – home Feb 25 '12 at 09:03
  • **The blank final field data may not have been initialized**... this is what i get.. – ngesh Feb 25 '12 at 09:05
  • 4
    If you are sick, do you send your wife to the doctor? Show us the real code. – JB Nizet Feb 25 '12 at 09:08
  • 1
    This code doesn't compile due to the Class in upper-case. So this is not the real code, or at least there is an other compile error, as already said by the other comments. – JB Nizet Feb 25 '12 at 09:13

4 Answers4

7

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";
   }
}
Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135
6

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.

Murat Derya Özen
  • 2,154
  • 8
  • 31
  • 44
3

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.

Ashwinee K Jha
  • 9,187
  • 2
  • 25
  • 19
2

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";
   }
}
Costis Aivalis
  • 13,680
  • 3
  • 46
  • 47