A
blank final is a final variable whose declaration lacks an
initializer.
public class BlankVariableEx { final int var; }
In
the above class variable 'var' is blank final variable, since it is
not initialized.
A
blank final variable can by static or non static.
Blank
final static variable
Blank
final static variable must be initialized in static block, else
compiler error thrown.
class Rectangle{ final static int width; }
When
you tries to compile the above program, below error thrown.
Rectangle.java:2: error: variable width not initialized in the default constructor final static int width; ^ 1 error
To
make the above program compiles fine, initialize the variable in
static block.
class Rectangle{ final static int width; static{ width = 100; } }
Blank
final Instance variable
A
blank final instance variable must be definitely assigned at the end
of every constructor of the class in which it is declared, otherwise
a compile-time error occurs.
class Rectangle{ final int width; }
When
you tries to compile the above program, compiler throws below error,
since the final blank variable is not initialized.
Rectangle.java:2: error: variable width not initialized in the default constructor final int width; ^ 1 error
class Rectangle{ final int width; Rectangle(){ width = 100; } Rectangle(int width){ } }
Above
program also won't compile, since width is not initialized in
parameterized constructor. Since a blank final instance variable must
be definitely assigned at the end of every constructor of the class
in which it is declared. To make the program compile fine,
initialize the variable width in All constructors like below.
class Rectangle{ final int width; Rectangle(){ width = 100; } Rectangle(int width){ this.width = width; } }
No comments:
Post a Comment