Can a final variable be initialized when an object

2019-01-19 05:45发布

问题:

how it can be possible that we can initialize the final variable of the class at the creation time of the object ?

Anybody can explain it how is it possible ? ...

回答1:

You must initialize a final variable once and only once. There are three ways to do that for an instance variable:

  1. in the constructor
  2. in an instance initialization block.
  3. when you declare it

Here is an example of all three:

public class X
{
    private final int a;
    private final int b;
    private final int c = 10;

    {
       b = 20;
    }

    public X(final int val)
    {
        a = val;
    }
}

In each case the code is run once when you call new X(...) and there is no way to call any of those again, which satisfies the requirement of the initialization happening once and only once per instance.



回答2:

Final variables which is not initialized during declaration are called blank final variable and must be initialized on all constructor either explicitly or by calling this(). Failure to do so compiler will complain as "final variable (name) might not be initialized".


As per Wikipedia

A final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a "blank final" variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared; otherwise, a compile-time error occurs in both cases.

Eg.

public class Sphere {

    // pi is a universal constant, about as constant as anything can be.
    public static final double PI = 3.141592653589793;  

    public final double radius;
    public final double xPos;
    public final double yPos;
    public final double zPos;

    Sphere(double x, double y, double z, double r) {
         radius = r;
         xPos = x;
         yPos = y;
         zPos = z;
    }

    [...]
}

For more details read the wiki page http://en.wikipedia.org/wiki/Final_(Java)



回答3:

Why not. Like this

public class GenericFoo{

    final int var;

    GenericFoo(){
        var = 100;
    }

}


回答4:

A final value is one which can only be set once, and only in the constructor. There is no reason it cannot be set by the constructor to any value you like.

If you had a value which you wanted to be a constant for all instance, you would make it static final and you would NOT be able to set it in a constructor. Perhaps you are confusing the two.



回答5:

You can initialize final instance variables before constructor completes.
According to JSL

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

Blank final variable in Java is a final variable which is not initialized while declaration

So there are 2 ways to do it.

way 1:In constructor

class Program {
    final int i3;   
    Program() {
        i3 = 10;
    }
}

way 2: In instance block

class Program {
       final int i3;   
       {
             i3 = 10;
        }
    }


回答6:

If you mean a static final member you can use a static initializer:

class Example {
  public final static Map<String,Object> C;

  static {
    C = new HashMap<>();
    C.put("hi", 5);
  }
}


回答7:

This is possible due to the way in which the JVM works internally and the way Java was designed.

After your code is compiled, the .class file generated will contain the bytecode representation of your code. A Class file is nothing but a bunch of bytes structured in a defined order which can be interpreted by the JVM.

In a Class File structure you will be able to find something called the Constant Pool, which is nothing but a symbolic reference table used by the JVM when classes are loaded. Your final variables will be found here whether they are initialized or not as a literal.

So now that you know this, let's move on and think of what the final modifier means, it means nothing but a way of telling the JVM that in this case a variable will be assigned a value and once this is done, a re-assignment operation on that variable will not be permitted, so as the Java Language documentation states, a final variable can be assigned a value once and only once.

Now that you have this background, in order to answer your question directly:

Whether your variable is an object or a primitive type, the value to a final variable which is not a class member (meaning is not static) will be automatically set by the JVM using the value in the runtime constant pool for your object OR if this variable is not initialized on declaration, then it will be required to be set when the constructor runs. All of this is possible because Java was designed this way to provide programmers some flexibility on variable assignment to avoid hard-coding and to provide a way to assign objects to final references.

Just as a final tip, stop thinking as final variables as constants in C++. They might seem similar but they are not, they are handled in completely different ways.



回答8:

As you know instance variable is associated with class object only ,And final keyword before variable means you can't change the value of variable so variable existence is only when object is created that's why we can assign the final variable value three ways as mentioned above before creation of object(eg. by static block,when you declare) or at the time of creation of object(eg. through constructor)



标签: java final