这是针对类似问题的规范问答,其中问题是隐藏的结果。
我在我的类中定义了两个字段,一个是引用类型,一个是原始类型。在类的构造函数中,我尝试将它们初始化为一些自定义值。
当我稍后查询这些字段的值时,它们会返回 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() 返回值 10,而 getElements() 返回一个正确初始化的数组实例。
最佳答案
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).
换句话说,作用域是一个编译时概念,它决定了一个名字可以用来指代某个程序实体的位置。
您发布的程序有多个声明。让我们从
开始private String[] elements;
private int capacity;
这些是 field声明,也称为 instance variables , IE。在 class body 中声明的一种成员. Java 语言规范声明
The scope of a declaration of a member
mdeclared in or inherited by a class typeC(§8.1.6) is the entire body ofC, including any nested type declarations.
这意味着您可以在 StringArray 的主体中使用名称 elements 和 capacity 来引用这些字段。
构造函数主体中的前两个语句
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.
在这种情况下, block 是构造函数体。但是构造函数主体是 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
dof a local variable or exception parameter namednshadows, throughout the scope ofd, (a) the declarations of any other fields namednthat are in scope at the point wheredoccurs, and (b) the declarations of any other variables namednthat are in scope at the point wheredoccurs but are not declared in the innermost class in whichdis declared.
这意味着名为 elements 的局部变量优先于名为 elements 的字段。表达式
elements = new String[capacity];
因此正在初始化局部变量,而不是字段。该字段被初始化为 default value对于它的类型,即。值 null。
在您的方法 getCapacity 和 getElements 中,您在它们各自的 return 语句中使用的名称指的是字段,因为它们的声明是程序中那个特定点的唯一范围内的。由于字段被初始化为 0 和 null,因此这些是返回的值。
解决方案是完全摆脱局部变量声明,从而让名称引用实例变量,正如您最初想要的那样。例如
public StringArray() {
capacity = 10;
elements = new String[capacity];
}
类似于上述情况,您可能有formal (constructor or method) parameters隐藏具有相同名称的字段。例如
public StringArray(int capacity) {
capacity = 10;
}
阴影规则状态
A declaration
dof a field or formal parameter namednshadows, throughout the scope ofd, the declarations of any other variables namednthat are in scope at the point wheredoccurs.
在上面的示例中,构造函数参数capacity 的声明隐藏了同样名为capacity 的实例变量的声明。因此不可能用简单的名称来引用实例变量。在这种情况下,我们需要用它的 qualified name 来引用它。 .
A qualified name consists of a name, a "." token, and an identifier.
在这种情况下,我们可以使用 primary expression this作为 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 都有阴影规则、方法和类型。
我的建议是尽可能使用唯一的名称,从而完全避免这种行为。
关于java - 当我在类的构造函数中声明并初始化字段时,为什么我的字段被初始化为 null 或默认值零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42117386/
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
在我的gem中,我需要yaml并且在我的本地计算机上运行良好。但是在将我的gem推送到rubygems.org之后,当我尝试使用我的gem时,我收到一条错误消息=>"uninitializedconstantPsych::Syck(NameError)"谁能帮我解决这个问题?附言RubyVersion=>ruby1.9.2,GemVersion=>1.6.2,Bundlerversion=>1.0.15 最佳答案 经过几个小时的研究,我发现=>“YAML使用未维护的Syck库,而Psych使用现代的LibYAML”因此,为了解决
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返
这是在Ruby中设置默认值的常用方法:classQuietByDefaultdefinitialize(opts={})@verbose=opts[:verbose]endend这是一个容易落入的陷阱:classVerboseNoMatterWhatdefinitialize(opts={})@verbose=opts[:verbose]||trueendend正确的做法是:classVerboseByDefaultdefinitialize(opts={})@verbose=opts.include?(:verbose)?opts[:verbose]:trueendend编写Verb
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢
它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput