Java,将null分配给对象和仅声明有什么区别 [英] Java, What is the difference between assigning null to object and just declaration

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

问题描述

有什么区别:

  • 对象 o = null;和
  • Object o;(只是声明)
  • Object o = null; and
  • Object o; (just declaration)

谁能回答我?

推荐答案

这取决于你声明变量的作用域.例如,局部变量没有默认值,在这种情况下,您必须手动分配null,而>instance variables 分配 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;
        localVariableObj1.getClass(); // illegal, a compiler error comes up as local vars don't get default values

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

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

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

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