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[?]
        

Can we Inherit Final Class in Java Language

Well we know that Inheritance is the very important part of any programming language, the same is with the Java programming language. We are talking about the final keyword usage. So the question is, can we inherit final class in Java language. If you had read my earlier post about final keyword then you should know that If we declare any class as final, it can’t be inherited. So the answer to the question is NO.  Since now you know the answer, you should try to practically prove it.

Check out this program code including final keyword: -

final class fin2
{

}
class derived extends fin2
{

}

Here we have two classes fin2 and derived. fin2 is a final class and derived is a simple class. They are trying to build inheritance relationship because

class derived extends fin2

Since fin2 is a final class, it cannot be inherited. If you compile this program, there will be an error message. Check out the compilation of this java program below

So now we know that final class can not be inherited in java language.


Share this Post[?]
        

« Previous PageNext Page »