Search This Blog

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?


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

4 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
  3. What this code does: This code has 2 constructors which can create the class TestFinalVar
    The 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.

    ReplyDelete
  4. Perfect, I like your reply.

    ReplyDelete