繁体   English   中英

最终的非静态数据成员

[英]Final non-static data member

如果不允许两次初始化finalstatic数据成员,那么如何在下面的示例中将x设置为所需的值?

class Temp6
{
    final int x;

    Temp6()
    {
        System.out.println(this.x);
        this.x=10;
    }

    public static void main(String[]s)
    {
        Temp6 t1 = new Temp6();
        System.out.println(t1.x);
    }
}

Java默认情况下将x的值设置为0 ,那么如何将其更改为10

在Java中标记为final的变量只能初始化一次。

只是简单地宣称xfinal int x; 不初始化它。 因此,在Temp6构造函数中分配给x是合法的。 但是,您将无法在构造x之后为x分配其他值。

也就是说,以下是对t1.x的赋值:

public static void main(String[] s) {
  Temp6 t1 = new Temp6();
  t1.x = 11; // ERROR
}

是不合法的。

在类构造函数中初始化最终变量。

public class Blam
{
    private final int qbert;

    public Blam(int qbertValue)
    {
        qbert = qbertValue;
    }
}

在代码中读取this.x应该会出错,因为final变量不会在声明时初始化。 t1.x应该为10因为x肯定在唯一构造函数的末尾分配。

您必须在构造函数中交换两行代码才能进行编译,那里将是10行。

class Temp {
    int x; // declaration and definition; defaulted to 0
    final int y; // declaration, not initialized
    Temp() {
         System.out.println(x); // prints 0
         x = 1;
         System.out.println(x); // prints 1
         x = 2; // last value, instance.x will give 2

         System.out.println(y); // should be a compiler error: The blank final field y may not have been initialized
         y = 3; // definite assignment, last and only value, instance.y will be 3 whereever used
         System.out.println(y); // prints 3
         y = 4; // compile error: The final field y may already have been assigned
    }
}

我以前从未想过,这里很有趣。 最终字段变量的行为类似于方法中的局部变量 ,必须在使用前对其进行显式赋值 (确定赋值很难形式化,请参阅JLS参考,但这很合逻辑)。

如果要从外部为x赋值,可以这样进行:

public class Temp {
    private final int x;
    public Temp(int x) {
        this.x = x;
    }
    public int getX() { return this.x; }

    public static void main(String[] args) {
        Temp temp = new Temp(10);
        System.out.println(temp.getX()); // 10
    }
}

final变量是java常量。 它们应该在类加载之前初始化。

final int x=10;

如果您的最终变量是静态的,则不必像在声明本身中给出值一样,则可以使用-

class Demo {
  static final int x;

   static {
        x = 10;
   }
}

在类加载时,静态块仅执行一次

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM