Final Instance variables

18 January 2012 By Nithya Vasudevan 1,021 views One Comment
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×
  • It should be assigned only once before constructor exits. i.e.) Assigned
    • during declaration (compile time constant)
    • inside constructor
    • inside initialization block
  • The value of a final instance variable is not necessarily known at the compile time i.e.) during declaration. This is known as blank final field which must be initialized before constructor exits.
class Car
{
	final int NO_OF_WHEELS = 4; //Compile time constant
	final double MAX_SPEED; //Blank final instance variable
	final double MIN_SPEED; //Blank final instance variable
	
	//initialization block
	{
		MIN_SPEED = 0; //mph
	}
	Car()
	{
		MAX_SPEED = 200; //mph
	}	
}
  • Final variable, NO_OF_WHEELS, initialized during declaration.
  • Final variable, MAX_SPEED, initialized inside the constructor.
  • Final variable, MIN_SPEED, initialized inside the initialization block.
  • Javin

    Indeed good post. final is a tricky keyword if used carefully it can boost performance of Java application. I have also shared my view as final keyword in Java let me know how do you find it.