Can a final variable be initialized when an object is created?

前端 未结 8 750
夕颜
夕颜 2020-12-09 10:29

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 ? ...<

8条回答
  •  执笔经年
    2020-12-09 10:57

    Final variables which is not initialized during declaration are called blank final variable and must be initialized on all constructor either explicitly or by calling this(). Failure to do so compiler will complain as "final variable (name) might not be initialized".


    As per Wikipedia

    A final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a "blank final" variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared; otherwise, a compile-time error occurs in both cases.

    Eg.

    public class Sphere {
    
        // pi is a universal constant, about as constant as anything can be.
        public static final double PI = 3.141592653589793;  
    
        public final double radius;
        public final double xPos;
        public final double yPos;
        public final double zPos;
    
        Sphere(double x, double y, double z, double r) {
             radius = r;
             xPos = x;
             yPos = y;
             zPos = z;
        }
    
        [...]
    }
    

    For more details read the wiki page http://en.wikipedia.org/wiki/Final_(Java)

提交回复
热议问题