Thursday, January 23, 2014

What is Wrong?

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?

My Answer : after 2 days

Posted by :
Nancy @ 2:29 pm 1/23/2014

2 comments:

  1. 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();).

    ReplyDelete
  2. Right, 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.

    ReplyDelete