Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

how it can be possible that we can initialize the final variable of the class at the creation time of the object ?

Anybody can explain it how is it possible ? ...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
167 views
Welcome To Ask or Share your Answers For Others

1 Answer

You must initialize a final variable once and only once. There are three ways to do that for an instance variable:

  1. in the constructor
  2. in an instance initialization block.
  3. when you declare it

Here is an example of all three:

public class X
{
    private final int a;
    private final int b;
    private final int c = 10;

    {
       b = 20;
    }

    public X(final int val)
    {
        a = val;
    }
}

In each case the code is run once when you call new X(...) and there is no way to call any of those again, which satisfies the requirement of the initialization happening once and only once per instance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...