可以构造函数返回一个null对象吗? [英] Can constructor return a null object?
问题描述
在查看一些旧代码时,我遇到了这个gem:
While looking through some old code I came across this gem:
MyObject o = new MyObject("parameter");
if (o == null) o = new MyObject("fallback parameter");
第二行在Eclipse中被标记为死代码,我明白为什么。没有异常似乎被明确抛出,并且 MyObject
构造函数不可能抛出任何种类的异常(例如 NullPointerException
s)。
The second line is marked in Eclipse as dead code, and I understand why. No exception seems to be explicitly thrown, and it isn't possible for the MyObject
constructor to throw any kind of exception (such as NullPointerException
s).
我的问题是为什么有空检查?以前是否可能在旧版本的Java中为构造函数返回null?或者这只是无用的和死代码?
My question is why there is a null check? Was it previously possible in an old version of Java for a constructor to return null? Or is this simply useless and dead code?
推荐答案
代码在任何版本的java都死了。构造函数不能返回 null
,即使从构造函数抛出异常,下一行也不会被调用。
The code is dead in any version of java. It's not possible for a constructor to return null
and even if an exception would be thrown from the constructor, the next line won't be called.
这篇关于可以构造函数返回一个null对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!