当我在 class' 构造函数中声明并初始化字段时,为什么我的字段被初始化为 null 或默认值零?

Why are my fields initialized to null or to the default value of zero when I've declared and initialized them in my class' constructor?

这是针对类似问题的规范问答,其中问题是 shadowing.


我在 class 中定义了两个字段,一个是引用类型,一个是原始类型。在 class' 构造函数中,我尝试将它们初始化为一些自定义值。

当我稍后查询这些字段的值时,它们返回 Java 的默认值,null 用于引用类型,0 用于原始类型。为什么会这样?

这是一个可重现的例子:

public class Sample {
    public static void main(String[] args) throws Exception {
        StringArray array = new StringArray();
        System.out.println(array.getCapacity()); // prints 0
        System.out.println(array.getElements()); // prints null
    }
}

class StringArray {
    private String[] elements;
    private int capacity;
    public StringArray() {
        int capacity = 10;
        String[] elements;
        elements = new String[capacity];
    }
    public int getCapacity() {
        return capacity;
    }
    public String[] getElements() {
        return elements;
    }
}

我希望 getCapacity() 到 return 值 10 和 getElements() 到 return 正确初始化的数组实例。

Java 程序中定义的实体(包、类型、方法、变量等)有 names。这些用于在程序的其他部分引用这些实体。

Java 语言为每个名字定义了一个 scope

The scope of a declaration is the region of the program within which the entity declared by the declaration can be referred to using a simple name, provided it is visible (§6.4.1).

换句话说,scope 是一个编译时概念,它决定了名称可以在何处用于引用某些程序实体。

您发布的程序有多个声明。让我们从

开始
private String[] elements;
private int capacity;

这些是 field declarations, also called instance variables, ie. a type of member declared in a class body。 Java 语言规范指出

The scope of a declaration of a member m declared in or inherited by a class type C (§8.1.6) is the entire body of C, including any nested type declarations.

这意味着您可以在 StringArray 的正文中使用名称 elementscapacity 来引用这些字段。

构造函数主体中的前两个语句

public StringArray() {
    int capacity = 10;
    String[] elements;
    elements = new String[capacity];
}

实际上是local variable declaration statements

A local variable declaration statement declares one or more local variable names.

这两个语句在您的程序中引入了两个新名称。碰巧这些名称与您的字段相同。在您的示例中,capacity 的局部变量声明还包含一个初始化程序,它 初始化局部变量 ,而不是同名字段。您名为 capacity 的字段的类型已初始化为 default value,即。值 0.

elements 的情况略有不同。局部变量声明语句引入了一个新名称,但是assignment expression?

呢?
elements = new String[capacity];

elements 指的是什么实体?

范围状态

的规则

The scope of a local variable declaration in a block (§14.4) is the rest of the block in which the declaration appears, starting with its own initializer and including any further declarators to the right in the local variable declaration statement.

在这种情况下,块是构造函数主体。但是构造函数主体是 StringArray 主体的一部分,这意味着字段名称也在范围内。那么 Java 如何确定您指的是什么?

Java引入Shadowing的概念来消歧义。

Some declarations may be shadowed in part of their scope by another declaration of the same name, in which case a simple name cannot be used to refer to the declared entity.

(一个简单名称是一个单一的标识符,例如elements。)

文档还指出

A declaration d of a local variable or exception parameter named n shadows, throughout the scope of d, (a) the declarations of any other fields named n that are in scope at the point where d occurs, and (b) the declarations of any other variables named n that are in scope at the point where d occurs but are not declared in the innermost class in which d is declared.

这意味着名为 elements 的局部变量优先于名为 elements 的字段。表达式

elements = new String[capacity];

因此正在初始化局部变量,而不是字段。该字段的类型被初始化为 default value,即。值 null.

在您的方法 getCapacitygetElements 中,您在各自的 return 语句中使用的名称指的是字段,因为它们的声明是该范围内唯一的字段程序中的特定点。由于字段被初始化为 0null,这些是返回的值。

解决方案是完全摆脱局部变量声明,从而让名称引用实例变量,正如您最初想要的那样。例如

public StringArray() {
    capacity = 10;
    elements = new String[capacity];
}

带构造函数参数的阴影

与上述情况类似,您可能有 formal (constructor or method) parameters 个同名的隐藏字段。例如

public StringArray(int capacity) {
    capacity = 10; 
}

阴影规则状态

A declaration d of a field or formal parameter named n shadows, throughout the scope of d, the declarations of any other variables named n that are in scope at the point where d occurs.

在上面的示例中,构造函数参数 capacity 的声明隐藏了同样名为 capacity 的实例变量的声明。因此不可能用简单的名称来引用实例变量。在这种情况下,我们需要用它的 qualified name.

来引用它

A qualified name consists of a name, a "." token, and an identifier.

在这种情况下,我们可以使用primary expression this as part of a field access expression来引用实例变量。例如

public StringArray(int capacity) {
    this.capacity = 10; // to initialize the field with the value 10
    // or
    this.capacity = capacity; // to initialize the field with the value of the constructor argument
}

每个 kind of variable、方法和类型都有 阴影 规则。

我的建议是尽可能使用唯一的名称,从而完全避免这种行为。

int capacity = 10; 在你的构造函数中声明了一个局部变量 capacity,它 shadows class.

的字段

补救措施是删除 int:

capacity = 10;

这将更改字段值。 class.

中的其他字段同上

你的 IDE 没有警告你这种阴影吗?

另一个被广泛接受的约定是向 class 成员添加一些前缀(或后缀 - 无论您喜欢什么),以将它们与局部变量区分开来。

例如 class 个前缀为 m_ 的成员:

class StringArray {
  private String[] m_elements;
  private int      m_capacity;

  public StringArray(int capacity) {
    m_capacity = capacity;
    m_elements = new String[capacity];
  }

  public int getCapacity() {
    return m_capacity;
  }

  public String[] getElements() {
    return m_elements;
  }
}


大多数 IDE 已经支持这种表示法,下面是针对 Eclipse

在java/c/c++中使用变量有两个部分。一种是声明变量,一种是使用变量(无论是赋值还是在计算中使用)。

声明变量时必须声明其类型。所以你会使用

int x;   // to declare the variable
x = 7;   // to set its value

使用变量时无需重新声明:

int x;
int x = 7;   

如果变量在同一个范围内,你将得到一个编译器错误;但是,正如您发现的那样,如果变量在不同的范围内,您将屏蔽第一个声明。