构造函数可以返回空对象吗? [英] Can constructor return a null object?
问题描述
在查看一些旧代码时,我发现了这个宝石:
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.
这篇关于构造函数可以返回空对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!