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 ? ...
Instantiation: The new keyword is a Java operator that creates the object. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.
Once you declare a variable final, after initializing it, you cannot modify its value further. Moreover, like instance variables, final variables will not be initialized with default values. Therefore, it is mandatory to initialize final variables once you declare them. If not a compile time error will be generated.
Uninitialized static final variable in Java: We can declare a static final variable and not initialize it right away. But this variable can only be initialized in a static block inside the code.
If you declare a variable as final, it is mandatory to initialize it before the end of the constructor.
You must initialize a final variable once and only once. There are three ways to do that for an instance variable:
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With