![](/img/trans.png)
[英]Can an instance of a class be created for testing without calling the constructor?
[英]Can a class be created without a default constructor?
下列类旨在“扩展” Math.random,不具有对象属性,因此不需要默认构造函数,但是存在一个构造函数(默认情况下)。
public class Mathematics {
public static long random( long lower, long upper ) {
return (
Math.min( lower, upper ) +
((long) (
( 1.0 +
(double) Math.abs( upper - lower )) *
Math.random() ))
);
}
}
有没有通用构造函数而无需默认构造函数的方法吗?
私有构造函数覆盖默认实例将不允许实例化。
public class Mathematics {
private Mathematics() { }
// Other stuff.
}
这很容易受到反射的影响(因为您可以更改可访问性),但是如果有人使用反射来实例化一类静态方法...
如评论中所述,如果您偏执,甚至可以抛出异常:
private Mathematics() thows IllegalAccessError {
throw IllegalAccessError(Mathematics.class.getName())
}
给它一个私有的无参数构造函数,它将和没有它一样好。
public class Foo {
private Foo() {}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.