0

Why does java allow this

public class A {

    private int i;

    public A(int i){

    }

}

but not this

public class A {

    private final int i;

    public A(int i){ // compile - time error

    }

}

What is the difference push the item to the stack when it is final ? Why doesn't it understand that A(i) is different than final int i ?

3 Answers 3

7

Variable in constructor has nothing to do with final class member the compile time error you are getting is due to final variable is not just initilized .

Try this it will work

private final int i=0;  

or

class A {

    private final int i;
       public A(int i){
       this.i = i;
    }

}  

or

class A {
    private final int i;
    public A(int i) {
    }//constructor over
    {//initilizer block
        i = 10;
    }
}

compiler needs final member to be initialized while it initialize object.

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

6 Comments

I know this but I'm confused with how java push the item to the stack because there is not any difference between calling any method
@hilal didn't get your comment , there is nothing to do with stack and method call here
@hilal, how do you mean? Your compile error comes from the fact that you your final member field i isn't assigned a value before the instance is constructed.
@hilal check here
I mean int i; f(int i){}. but I forget to initialize the final while init.
|
6

final member fields must be assigned before an instance's constructor finishes.

From Java Language Specification, 3rd Edition

8.3.1.2 final Fields

A field can be declared final (§4.12.4). Both class and instance variables (static and non-static fields) may be declared final. It is a compile-time error if a blank final (§4.12.4) class variable is not definitely assigned (§16.8) by a static initializer (§8.7) of the class in which it is declared.

A blank final instance variable must be definitely assigned (§16.9) at the end of every constructor (§8.8) of the class in which it is declared; otherwise a compile-time error occurs.

Comments

6

It will allow the second snippet when you assign a value for i in the constructor:

public class A {

    private final int i;

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

}

Note that this is how you create Immutable objects.

Comments

Your Answer

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