When a class declares only private instance constructors, it is not possible
for other classes to derive from that
class or to create instances of that class (an exception being classes
nested within that class). [Example: Private
instance constructors are commonly used in classes that contain only static
members. For example:
public class Trig
{
private Trig() {} // Prevent instantiation
public const double PI = 3.14159265358979323846;
public static double Sin(double x) {?}
public static double Cos(double x) {?}
public static double Tan(double x) {?}
}
The Trig class groups related methods and constants, but is not intended to
be instantiated. Therefore, it declares
a single empty private instance constructor. end example] At least one
instance constructor must be declared to
suppress the automatic generation of a default constructor.
for other classes to derive from that
class or to create instances of that class (an exception being classes
nested within that class). [Example: Private
instance constructors are commonly used in classes that contain only static
members. For example:
public class Trig
{
private Trig() {} // Prevent instantiation
public const double PI = 3.14159265358979323846;
public static double Sin(double x) {?}
public static double Cos(double x) {?}
public static double Tan(double x) {?}
}
The Trig class groups related methods and constants, but is not intended to
be instantiated. Therefore, it declares
a single empty private instance constructor. end example] At least one
instance constructor must be declared to
suppress the automatic generation of a default constructor.
本文探讨了使用私有实例构造函数防止类被继承或实例化的概念。通过示例说明了如何利用私有构造函数来保护仅包含静态成员的类,确保这些类不会被误用。
1286

被折叠的 条评论
为什么被折叠?



