Delay initialization of Final Variable are Possible only within Constructor
Yeah we are going to practically prove another statement of final keyword called Delay initialization of final variable are possible only within constructor.
We are going to write total 3 programs to prove it.
Program 1: -
class fin4
{
final int a=10;
void show()
{
System.out.println(a);
}
static public void main(String[] args)
{
new fin4().show();
}
}
If you compile this program, you will get output of 10 because there is no any error in the program but check out the program no. 2 and try finding out the differences.
class fin4
{
final int a;
void show()
{
a=10;
System.out.println(a);
}
static public void main(String[] args)
{
new fin4().show();
}
}
Here, in this program we didn’t assigned any value to the data member a in the first place so we are assigning value of 10 to local variable a.
a=10;
Remember variable a is already declared as final in the first place so the value can’t be assigned to a in any other place except constructor. So we will get an error message that cannot assign value to final variable a. Also check out the screen shot of compilation of this final keyword program 2.
Now there is only one way to assign value to a i.e., within construction. Check out this program 3.
class fin5
{
final int a;
fin5()
{
a=10;
}
void show()
{
System.out.println(a);
}
static public void main(String[] args)
{
new fin5().show();
}
}
Here we have called a constructor
fin5()
{
a=10;
}
and is assigning the value to variable a. There is legal way in final keyword. If you compile this program, you will not get any error. The output will be zero. Also check out the screen shot of compilation and output of the java program.
So now we know that Delay initialization of Final Variable are Possible only within Constructor.
Share this Post[?]




