public Double squareRoot(Double d)
{
return new Double (Math.sqrt(d.doubleValue()));
}
“返新”的目的是什么?如果删除“new”,它仍然有效吗?
最佳答案
是的,事实上您可以删除更多代码:
public Double squareRoot(Double d)
{
return Math.sqrt(d);
}
即使 Math.sqrt
返回一个 double
而不是 Double
。这是通过名为 Autoboxing 的 java 功能完成的。 。
但正如 @assylias 所指出的,您询问是否可以仅删除 new
关键字。答案是否定的。这不会编译:
public Double squareRoot(Double d)
{
return Double (Math.sqrt(d.doubleValue()));
}
错误是“需要方法调用”。您不能将类的构造函数作为方法来调用。您只能通过在构造函数前面放置 new
关键字来调用它。
关于java - 返新目的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15794291/