为什么实例变量在java中有默认值? [英] Why do instance variables have default values in java?

查看:382
本文介绍了为什么实例变量在java中有默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在类中声明的变量具有默认值,但是在方法中声明的变量(称为局部变量)在Java中没有默认值?

Why do variables declared in a class have default values, but the variables declared inside methods, said to be "local variables", don't have default values in Java?

例如

class abc
{
   int a;

   public static void main(String ss[])
   {
        int b;

          abc aa=new abc();
          System.out.println(aa.a);
          System.out.println(b);
    }
 }

在上面的示例变量 a 的默认值为0,但变量 b 给出可能未初始化的错误。

In this above example variable a has default value of 0 but variable b gives error that it might not have been initialized.

推荐答案

所有成员变量都必须加载到堆中,以便在创建类的实例时,必须使用默认值进行初始化。在局部变量的情况下,它们不会被加载到堆中,而是存储在堆栈中,直到它们在java 7之前被使用,因此我们需要显式初始化它们。
现在Java Hotspot Server Compiler执行转义分析并决定在堆栈而不是堆上分配一些变量。

All member variable have to load into heap so they have to initialized with default values when an instance of class is created. In case of local variables, they don't get loaded into heap they are stored in stack until they are being used before java 7, so we need to explicitly initialize them. Now the "Java Hotspot Server Compiler" performs "escape analysis" and decides to allocate some variables on the stack instead of the heap.

这篇关于为什么实例变量在java中有默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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