public class TestFinalVar {
private final int MAX_CAPACITY;
public TestFinalVar(){
MAX_CAPACITY=100;
}
public TestFinalVar(int capacity){
this();
MAX_CAPACITY=capacity;
}
}
The code does not compile. What do you think is NOT Right?
Posted by :
Nancy @ 2:29 pm 1/23/2014
Assignment to the final field MAX_CAPACITY in the parameterized constructor (MAX_CAPACITY=capacity;), when it has already been assigned a value through the parameterless constructor invocation (this();).
ReplyDeleteRight, thats the answer. final variable can be assigned values once. In this case MAX_CAPACITY is assigned value 100 by default constructor due to constructor chaining. In parameterized constructor, code is assigning the value to final variable second time... hence error.
ReplyDeleteWhat this code does: This code has 2 constructors which can create the class TestFinalVar
ReplyDeleteThe second constructor"
public TestFinalVar(int capacity){
this();
MAX_CAPACITY=capacity;
}
"
calls the first constructor with the this() function.
The reason this will not compile is because final keyword makes it so when a variable is set, that it cannot be unset by java.
You need to remove final keyword in: private final int MAX_CAPACITY; or
remove this(); constructor call
for the code to compile.
Perfect, I like your reply.
ReplyDelete