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

查看:117
本文介绍了为什么必须在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?

推荐答案

有一个最近关于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.

基本上,要求在读取变量之前为变量赋值是一件好事。这意味着你不会意外地阅读你不想要的东西。是的,变量可以有默认值 - 但是如果它能够证明你正在尝试读取可能尚未分配的内容,那么编译器是否能够更好地捕获你的bug?如果你想给一个局部变量一个默认值,你总是可以明确地赋值。

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.)

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

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