-1

I have two final variables declared at class level but they are not initialized.
So, now when I try to create default constructor for that class, it is giving an error saying
The blank final field may not have been initialized.

Why this error occurs? Why need to initialize final variables in constructor?

I have another query also that is, is it not possible to create an instance without a default constructor? Even if we have parameterized constructor?

Saikiran Gosikonda
  • 928
  • 1
  • 11
  • 29
  • 3
    refer http://stackoverflow.com/questions/26935453/the-blank-final-field-initial-may-not-have-been-initialized – sasikumar Feb 26 '16 at 10:43
  • You have to always initialize final fields with constructor. Final fields must have been assigned during object instantations. Regardless of constructor - every final field must have a value assigned. – mlewandowski Feb 26 '16 at 10:44
  • @mlewandowski you don't have to do it with a constructor - you can directly assign the field a value or use an initializer block (which are basically equivalent). – Andy Turner Feb 26 '16 at 10:45

2 Answers2

1

Why need to initialize final variables in constructor?

A final field has to be initialised in the constructor because this is what final has been defined to mean.

You don't have to set the final feilds in the default constructor if you call a constructor which does e.g.

class A {
   final int a;

   public A() {
       this(0);
   }

   public A(int a) {
       this.a = a;
   }
}

is it not possible to create an instance without a default constructor?

Yes. There is a number of way to do this, most often by calling a constructor which takes parameters.

Even if we have parameterized constructor?

In this case, you will only have a constructor which takes no parameters if you define one.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Final variable are those variable which can not be changed once object is initialized. So any how you will have to initialize the final variable. If you are providing default constructor as well as parameterized consructor, you must have to initialize those variable, Since you can not change the value later.

Rahul
  • 3,479
  • 3
  • 16
  • 28