为什么必须在 Java 中初始化局部变量,包括原语? [英] Why must local variables, including primitives, always be initialized in Java?

查看:37
本文介绍了为什么必须在 Java 中初始化局部变量,包括原语?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么必须在 Java 中初始化局部变量,包括原语?为什么同样不适用于实例变量?

Why must local variables, including primitives, always be initialized in Java? Why is the same not applicable in the case of instance variables?

推荐答案

基本上,要求在读取变量之前为其赋值是一件好事.这意味着您不会意外阅读您不打算阅读的内容.是的,变量可以有默认值 - 但是如果编译器能够证明您正在尝试读取可能尚未分配的内容,那么编译器能够捕获您的错误不是更好吗?如果你想给一个局部变量一个默认值,你总是可以显式赋值.

Basically, requiring a variable to be assigned a value before you read it is a Good Thing. It means you won't accidentally read something you didn't intend to. Yes, variables could have default values - but isn't it better for the compiler to be able to catch your bug instead, if it can prove that you're trying to read something which might not have been assigned yet? If you want to give a local variable a default value, you can always assign that explicitly.

现在这对局部变量没问题——但是对于实例变量和静态变量,编译器无法知道调用方法的顺序.会在getter"之前调用属性setter"吗?它无法知道,因此无法提醒您注意危险.这就是为什么默认值 用于实例/静态变量 - 至少你会得到一个已知值(0、false、null 等),而不仅仅是当时内存中发生的任何事情."(它还消除了读取未明确擦除的敏感数据的潜在安全问题.)

Now that's fine for local variables - but for instance and static variables, the compiler has no way of knowing the order in which methods will be called. Will a property "setter" be called before the "getter"? It has no way of knowing, so it has no way of alerting you to the danger. That's why default values are used for instance/static variables - at least then you'll get a known value (0, false, null etc) instead of just "whatever happened to be in memory at the time." (It also removes the potential security issue of reading sensitive data which hadn't been explicitly wiped.)

最近有一个关于这个的问题C#... - 也阅读那里的答案,因为它基本上是一样的.您可能还会发现 埃里克·利珀特 (Eric Lippert) 最近的博文 很有趣;它至少在相同的区域附近,即使它的推力略有不同.

There was a question about this very recently for C#... - read the answers there as well, as it's basically the same thing. You might also find Eric Lippert's recent blog post interesting; it's at least around the same area, even though it has a somewhat different thrust.

这篇关于为什么必须在 Java 中初始化局部变量,包括原语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆