gpt4 book ai didi

java - 在匿名类中限定此名称与简单名称

转载 作者:行者123 更新时间:2023-11-30 03:04:31 26 4
gpt4 key购买 nike

在下面的代码中,为什么 Java 认为简单名称 numCows 可能未初始化?为什么使用限定-this 可以防止错误?

import java.util.function.Function;

public class CowFarm {

private final int numCows;

public CowFarm(int numCows) {
this.numCows = numCows;
}

// Fails to compile
//
// CowFarm.java:12: error: variable numCows might not have been initialized
public final Function<Integer, Integer> MULTIPLY_COWS = (k -> numCows * 2);

// Works fine
public final Function<Integer, Integer> DIVIDE_COWS = (k -> CowFarm.this.numCows * 2);
}

最佳答案

来自Java Specification :

For every access of a... blank final field x, x must be definitely assigned before the access, or a compile-time error occurs... Such an assignment is defined to occur if and only if either the simple name of the variable (or, for a field, its simple name qualified by this) occurs on the left hand side of an assignment operator.

出现在类声明中赋值运算符 (=) 左侧的

final 字段在类构造函数中的 final 字段之前实例化。由 this 键限定的 final 字段在类构造函数之后实例化。考虑以下示例:

public class Foo{

//Instantiated before constructor
final Bar bar1 = new Bar();

//Instantiated by constructor
final Bar bar2;

//Instantiated after constructor
final Bar bar3 = this.bar2;

//Compile time error
final Bar bar3 = bar2;

public Foo(Bar bar) {
this.bar2 = bar;
}
}

就您而言,问题在于当您尝试实例化 MULTIPLY_COWS 时,numCows明确分配this 限定符确保在实例化 MULTIPLY_COWS 时明确分配 numCows

// This works fine, as well
public final Function<Integer, Integer> DIVIDE_COWS = (k -> this.numCows * 2);

关于java - 在匿名类中限定此名称与简单名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35144714/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com