Google+

91. 'final' instance variable







If an instance variable is declared as 'final' , then the instance  variable will behave like a constant  by preventing its value from being modified.

Note - As per the coding convention, we've to mention the instance variables specified as 'final' in upper case as shown below:

     final int COUNT = 5;

Lets implement this on Eclipse IDE:

1. Create a class 'FinalDemo' under any project as shown below:



2. Declare an instance variable 'COUNT' and specify it as 'final' as shown below:



3. Try to re-assign a different value to 'COUNT' variable which is specified as 'final' as shown below:



4. Observe that an error is displayed and hover your mouse over the error to read the error details as shown  below:



After looking at this error, its very clear that  instance variables specified as 'final' can be assigned a value only once.

Note - 'final' is one of the non-access specifiers in Java. 

Download this project:

Click here to download this project containing the class file used in this post (You can download the project and import into Eclipse IDE on your machine)




Please comment below to feedback or ask questions.

'length' array attribute will be explained in the next post.



2 comments:

viki said...

Is final statement can declared inside the normal class.

ex:
public class finalDemo
{
final int i=5;

i=6;
}

Arun Motoori said...

@viki - Yes, variable can be declared as final inside the class as shown below:

public class Final_Class {


final int I = 5;

}

Its similar to regular instance variable usage, expect the value assigned to it cannot be changed.