Java Reference
In-Depth Information
The above code for the
Test2
class would not compile. The compiler generates an error message, which reads
as
variable y might already have been assigned
. Let's consider creating an object of the
Test2
class as
Test2 t = new Test2(30);
There is no issue in creating an object of the
Test2
class by invoking the one-arg constructor. The blank
final
instance variable
y
is initialized only once. Let's create an object of the
Test2
class.
Test2 t2 = new Test2();
When the no-args constructor is used, it calls the one-arg constructor, which initializes y to
20
. The no-args
constructor initializes
y
again to 10, which is the second time initialization for
y
. For this reason, the above code for
the
Test2
class would not compile. You need to remove the initialization of
y
from no-args constructor and the code
would compile. The following is the modified code for the
Test2
class that would compile:
public class Test2 {
private final int y;
public Test() {
this(20); // Another constructor will initialize y
}
public Test(int z) {
y = z; // Initialize y
}
}
final Class Variables
You can declare a class variable
final
and
blank final
. You must initialize a blank
final
class variable in one of the
static
initializers. If you have more than one
static
initializer for a class, you must initialize all the blank
final
class
variables only once in one of the
static
initializers.
The following code for the
Test3
class shows how to deal with a
final class
variable. It is customary to use all
uppercase letters to name
final
class variables. It is also a way to define constants in Java programs. The Java class
library has numerous examples where it defines
public static final
variables to use them as constants.
public class Test3 {
public static final int YES = 1;
public static final int NO = 2;
public static final String MSG;
static {
MSG = "I am a blank final static variable";
}
}