Java Reference
In-Depth Information
The following code would not compile because it initializes y more than once inside two instance initializers:
public class Test2 {
private final int y;
{
y = 10; // Initialized y for the first time
}
{
y = 10; // An error. Initializing y again
}
The above code may seem legal to you. However, it is not legal because two instance initializers are initializing
y , even though both of them sets y to the same value 10 . The rule is about number of times a blank final instance
variable should be initialized, irrespective of the value being used for its initializations. Since all instance initializers
are executed when an object of the Test2 class is created, y will be initialized twice, which is not legal.
The following code for the class Test2 with two constructors would compile:
public class Test2 {
private final int y;
public Test() {
y = 10; // Initialize y
}
public Test(int z) {
y = z; // Initialize y
}
}
The above code initializes the blank final instance variable y in both constructors. It may seem that y is being
initialized twice—once in each constructor. Note that y is an instance variable and one copy of y exists for each object
of the Test2 class. When an object of the Test2 class is created, it will use one of the two constructors, not both.
Therefore, for each object of the Test2 class, y is initialized only once.
Below is the modified code for the Test2 class, which presents a tricky situation. Both constructors initialize the
blank final instance variable y . The tricky part is that the no-args constructor calls another constructor.
public class Test2 {
private final int y;
public Test() {
this(20); // Call another constructor
y = 10; // Initialize y
}
public Test(int z) {
y = z; // Initialize y
}
}
Search WWH ::




Custom Search