Final Instance variables

  • 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.

Leave a Comment