Java 中括号的作用是:Dollar 美元 = (Dollar) 对象;
在使用 Kent Beck 的《TDD by Examples》一书时,我遇到了一些我不理解的 Java 代码。
public boolean equals(Object object) {
Dollar dollar= (Dollar) object;
return amount == dollar.amount;
}
有人可以向我解释一下 Dollar Dollar= (Dollar) object;
中的括号是什么意思吗?
While working with Kent Becks Book TDD by Example, I encountered some Java Code I did not understand.
public boolean equals(Object object) {
Dollar dollar= (Dollar) object;
return amount == dollar.amount;
}
Could someone please explain to me what the parenthesis in Dollar dollar= (Dollar) object;
mean?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个显式类型转换。基本上它是说“虽然'object'是用
Object
类型声明的,但我知道它实际上是Dollar
类型,所以可以将它分配给变量'dollar'” 。没有括号(实际上,这些是括号,括号看起来像
[]
或<>
,分别取决于它们是“方括号”还是“尖括号”) ,编译器会在该行报告错误。It's an explicit typecast. Basically it's saying that "although 'object' was declared with type
Object
, I know that it's actually of typeDollar
so it's okay to assign it to the variable 'dollar'".Without the brackets (actually, those are parenthesis, brackets look like
[]
or<>
depending if they are "square brackets" or "angle brackets", respectively), the compiler would report an error on that line.他们将对象转换为括号中的类型。
在您的示例中,它们告诉 java
object
应该是Dollar
类型They cast the object to the type in parenthesis.
In your example, they tell java that
object
should be of typeDollar
由于
equals()
函数使用“Object”类型作为object
参数,因此(Dollar) 对象
告诉美元变量object
确实属于Dollar
类。正如其他回复所说,这种表示法称为类型转换,Java 编译器使用它来确保在将一个变量分配给另一个变量时使用正确的类型。就其价值而言,作为一个新手程序员,这些东西可能看起来非常令人困惑,但在一段时间后它确实开始陷入困境。
Because the
equals()
function uses the type "Object" for theobject
parameter, The(Dollar) object
tells the dollar variable thatobject
is indeed of theDollar
class. As the other replies have said, the notation is called a typecast, and is used by the Java compiler to ensure that you are using the correct type when you assign one variable to another.For what it's worth, as a novice programmer this stuff can seem very confusing, but it does start to sink in after a while.