因为构建子类对象的方式可能与构建超类的方式不同。您可能不希望子类的客户端能够调用超类中可用的某些构造函数。
一个愚蠢的例子:class Super {
protected final Number value;
public Super(Number value){
this.value = value;
}}class Sub {
public Sub(){ super(Integer.valueOf(0)); }
void doSomeStuff(){
// We know this.value is an Integer, so it's safe to cast.
doSomethingWithAnInteger((Integer)this.value);
}}// Client code:Sub s = new Sub(Long.valueOf(666L)):
// Devilish invocation of Super constructor!s.doSomeStuff();
// throws ClassCastException
或者更简单:class Super {
private final String msg;
Super(String msg){
if (msg == null) throw new NullPointerException();
this.msg = msg;
}}class Sub {
private final String detail;
Sub(String msg, String detail){
super(msg);
if (detail == null) throw new NullPointerException();
this.detail = detail;
}
void print(){
// detail is never null, so this method won't fail
System.out.println(detail.concat(": ").concat(msg));
}}// Client code:Sub s = new Sub("message");
// Calling Super constructor - detail is never initialized!s.print();
// throws NullPointerException
从本例中可以看出,您需要某种方式声明“我想继承这些构造函数”或“我想继承除这些构造函数之外的所有构造函数”,然后还必须指定默认构造函数继承首选项,以防有人在超类中添加新构造函数.或者,如果您想要“继承”它们,那么只需要从超类中重复构造函数,这可以说是更明显的方法。