What conditions cause object instantiation to return null? [duplicate]

回眸只為那壹抹淺笑 提交于 2019-12-13 13:48:42

问题


Is it possible for the following line to return null?

MyClass obj = new MyClass();

If so, what conditions would cause a return value of null?


回答1:


It's impossible for new to return null, assuming the VM is functioning correctly.

From section 15.9.4 of the Java Language Specification:

The value of a class instance creation expression is a reference to the newly created object of the specified class. Every time the expression is evaluated, a fresh object is created.




回答2:


No, this can't return null. It could, however, throw an exception and depending on how you handle that exception the obj reference might still be null after the exception is handled (if you leave the code block, e.g. by not catching the exception, the obj reference would cease to exist and thus it wouldn't matter).

Reasons for exceptions in a constructor are manifold, for example if you run out of memory (in which case you get an OutOfMemoryError) or if you access an uninitialized field which is still null and would cause a NullPointerException.




回答3:


a static initializer error

like

public class MyClass {

static {
  throw new Error("Error");
}

}

public class MyClass2 {

  static MyClass test=new MyClass();

}

You cannot ask your question without specifying the context. In an application server, the above will creare Myclass2 with test=null. Why ? Because the Error is typically trapped by the application server.




回答4:


Short answer - NO.

But you can throw an exception from a constructor, in which case, if obj was initially assigned to null, it will remain null.




回答5:


In my opinion it is impossible. If somehow you run out of memory in Java you will get OutOfMemoryError exception.



来源:https://stackoverflow.com/questions/9183930/what-conditions-cause-object-instantiation-to-return-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!