构造函数可以是私有的吗?私有构造函数如何有用?
当前回答
私有构造函数防止调用者显式实例化类 请参阅PrivateConstructor的进一步信息
其他回答
受到Robert C. Martin的“Clean Code”的启发,我整理了一个例子:
/**
When overloading constructors, it is best practise to only allow the use of
different constructors than the standart one by explicitly enforcing the
useage of a static function to highlight the use of the overloaded constructor
in example:
Animal a = Animal.CreateInsectOrArachnia(2, "black", 8); //hatch a black widow
*/
class Animal
{
private int size;
private String color;
private int legs;
public Animal(int size, String color)
{
this.size = size;
this.color = color;
this.legs = 4;
}
//will prevent the instanciation of Animal with this constructor
private Animal(int size, String color, int legs)
{
this.size = size;
this.color = color;
this.legs = legs;
}
public static Animal CreateInsectOrArachnia(int size, String color, int legs)
{
return new Animal (size, color, legs);
}
}
Martins明确指出,应该阻止用户访问“标准构造函数”以外的构造函数,并应该强制使用静态初始化函数,以强调“你所做的可能没有错,但它与该类的预期使用不同”。
[他没有使用这个确切的措辞,我试图把它挤进这个定义-对不起,罗伯特:^)]
作为旁注,完全可以将类中唯一的构造函数(即标准构造函数)完全声明为private,并让静态函数返回类实例-请参阅单例模式。但是,非常不鼓励实现单例模式,除非在一些通信只在一个方向上流动的用例中,例如在编写记录器类时
私有构造函数防止调用者显式实例化类 请参阅PrivateConstructor的进一步信息
如果一个类中的所有方法都是静态的,那么私有构造函数是个好主意。
是的,它用于防止实例化和随后重写。这最常用于单例类中。
构造函数可以是私有的吗?私有构造函数如何有用?
是的,它可以。我认为这是另一个有用的例子:
//... ErrorType.java
public enum ErrorType {
X,
Y,
Z
}
//... ErrorTypeException.java
import java.util.*;
import java.lang.*;
import java.io.*;
//Translates ErrorTypes only
abstract public class ErrorTypeException extends Exception {
private ErrorTypeException(){}
//I don't want to expose thse
static private class Xx extends ErrorTypeException {}
static private class Yx extends ErrorTypeException {}
static private class Zx extends ErrorTypeException {}
// Want translation without exposing underlying type
public static Exception from(ErrorType errorType) {
switch (errorType) {
case X:
return new Xx();
case Y:
return new Yx();
default:
return new Zx();
}
}
// Want to get hold of class without exposing underlying type
public static Class<? extends ErrorTypeException> toExceptionClass(ErrorType errorType) {
switch (errorType) {
case X:
return Xx.class;
case Y:
return Yx.class;
default:
return Zx.class;
}
}
}
在上面的例子中,它阻止抽象类被任何派生类实例化,除了它的静态内部类。抽象类不能是final类,但在这种情况下,私有构造函数使它有效地成为所有非内部类的final类
推荐文章
- 如何在java中格式化持续时间?(如格式H:MM:SS)
- urlencoder .encode(字符串)已弃用,我应该使用什么代替?
- javax.transaction.Transactional vs . org.springframework.transaction.annotation.Transactional
- Java 8接口方法中不允许“同步”的原因是什么?
- 如何找到Java堆大小和内存使用(Linux)?
- 使用Enum实现单例(Java)
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?
- Spring MVC -如何获得所有的请求参数在一个地图在Spring控制器?
- 如何在Java中按两个字段排序?
- 文件之间的差异。路径中的分隔符和斜杠
- 在方法参数中使用NotNull注释
- Spring MVC中处理可选参数的@RequestParam
- Tomcat:如何查找正在运行的Tomcat版本?
- “java”、“javaw”和“javaws”之间有什么区别?