Java,将null赋给object和声明之间的区别是什么 [英] Java, What is the difference between assigning null to object and just declaration

查看:96
本文介绍了Java,将null赋给object和声明之间的区别是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别:


  • 对象o = null ;和

  • 对象o; (只是声明)

  • Object o = null; and
  • Object o; (just declaration)

任何人都可以回答我吗?

Can anyone please answer me?

推荐答案

这取决于您声明变量的范围。例如,局部变量没有默认值,在这种情况下,您必须手动分配 null ,其中在实例变量的情况下分配null是多余的,因为实例变量获得默认值。

It depends on the scope where you declare the variable. For instance, local variables don't have default values in which case you will have to assign null manually, where as in case of instance variables assigning null is redundant since instance variables get default values.

public class Test {
    Object propertyObj1;
    Object propertyObj2 = null; // assigning null is redundant here as instance vars get default values 

    public void method() {
        Object localVariableObj1;
        Object localVariableObj1.getClass(); // illegal, a compiler error comes up as local vars don't get default values

        Object localVariableObj2 = null;
        Object localVariableObj2.getClass(); // no compiler error as localVariableObj2 has been set to null

        propertyObj1.getClass(); // no compiler error
        propertyObj2.getClass(); // no compiler error
    }
}

这篇关于Java,将null赋给object和声明之间的区别是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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