Abhishek Singh
Abhishek Singh

Reputation: 9775

final reference variables must be initialized before constructor complete ? Why?

A final reference variable must be initialized before constructor is complete.

That means the same can be done while

  1. Along with instance variable declaration

    final Foo foo = new Foo()
    
  2. In initializer block

    {
        foo = new Foo();
    }
    
  3. in a constructor

    public Example()
    {
        foo = new Foo();
    }
    

Correct me if i am wrong ? What is the reason for same ? Are the rules same for a primitive final variable like int or float ?

Upvotes: 1

Views: 319

Answers (2)

Junaid S.
Junaid S.

Reputation: 2652

A final reference variable must be initialized before constructor is complete.

Yes ... it should be. But keep in mind that

static final ClassAbc myObj = new ClassAbc(); // This should be initialize while declaring
// because it is static and visible for every time (donot need object to call it)

The point/reason is that final variable SHOULD be initialized BEFORE it is even accessable (means 'can be used' ) ....

Are the rules same for a primitive final variable like 'int' or 'float' ?

Yes rules are same for primitive and non-primitive types.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692281

No, an instance variable can't be accessed from a static block. What you call a static block is in fact an instance initializer block.

The reason for this rule is that the definition of a final field is a field that can be assigned only once. And if it was possible to initialize it after a constructor, in a method, the compiler would have no way to know that this method is called only once, and that another method doesn't try to read the value of the field before it's initialized, making the whole concept of final useless.

Upvotes: 3

Related Questions