Java默认值混淆,为什么没有函数作用域变量? [英] Java default values confusion, why none for function scoped variables?

查看:111
本文介绍了Java默认值混淆,为什么没有函数作用域变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对我认为不一致的原因感到困惑。

I'm having some confusion with the reasoning behind what seems to me to be an inconsistency.

例如

public class Test
{
    static int a;
    public static void main(String[] args)
    {
        System.out.println(a);
    }
}

因此,将按预期打印0。但是说我们有这个,

So that will print out 0, as expected. But say we had this instead,

public class Test
{

    public static void main(String[] args)
    {
        int a;
        System.out.println(a);
    }
}

这不会为我编译,抱怨说尚未初始化。我期待它打印出0 ...

This won't compile for me, complaining that a hasn't been initialized. I was expecting it to print out 0...

这引出了一些问题:

1)为什么函数范围变量没有默认值?

1) Why don't function scoped variables have default values?

2)静态关键字可能是原因吗?为什么?

2) Could the static keyword be the reason? And why?

推荐答案

Java语言规范解释了默认变量的初始值

The Java Language Specification explains the default Initial values of Variables


每个类变量,实例变量或数组组件都是
,在创建时使用默认值进行初始化(§15.9,§15.10):

Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10):

对于type byte,默认值为零,即
(byte)0的值。

For type byte, the default value is zero, that is, the value of (byte)0.

对于type short,默认值为零,即
(短)0的值。

For type short, the default value is zero, that is, the value of (short)0.

对于int类型,默认值为零,即0。

For type int, the default value is zero, that is, 0.

对于long类型,默认值为零,即0L。

For type long, the default value is zero, that is, 0L.

对于类型float,默认值为正零,即0.0f。

For type float, the default value is positive zero, that is, 0.0f.

对于double类型,默认值为正零,即0.0d。

For type double, the default value is positive zero, that is, 0.0d.

对于char类型,de fault值是空字符,即
'\ u0000'。

For type char, the default value is the null character, that is, '\u0000'.

对于类型boolean,默认值为false。

For type boolean, the default value is false.

对于所有引用类型(§4.3),默认值为null。

For all reference types (§4.3), the default value is null.

还有在 b

and also states

(§15.26),可以使用明确
赋值(§16)的规则进行验证。

A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16).

您的问题都可以通过因为JLS这么说来回答。

Both your questions can be answered by "Because the JLS says so".

更完整的答案如下:

类是对状态和行为的描述。对象是实际数据。如果你创建一个对象,它必须具有明确的状态,它不能处于未初始化的状态。

A Class is a description of state and behavior. An object is the actual data. If you create an object, it must have definitive state, it cannot be in an uninitialized state.

这篇关于Java默认值混淆,为什么没有函数作用域变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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