Java 构造函数继承

Java 构造函数继承

问题描述:

我想知道为什么在java构造函数中没有继承?你知道什么时候有这样的课程:

I was wondering why in java constructors are not inherited? You know when you have a class like this:

public class Super {

  public Super(ServiceA serviceA, ServiceB serviceB, ServiceC serviceC){
    this.serviceA = serviceA;
    //etc
  } 

}

稍后当你从Super 继承时,java 会抱怨没有定义默认构造函数.解决方案显然类似于:

Later when you inherit from Super, java will complain that there is no default constructor defined. The solution is obviously something like:

public class Son extends Super{

  public Son(ServiceA serviceA, ServiceB serviceB, ServiceC serviceC){
    super(serviceA,serviceB,serviceC);
  }

}

这段代码是重复的,不是 DRY 和无用的(恕我直言)......所以又带来了这个问题:

This code is repetitive, not DRY and useless (IMHO)... so that brings the question again:

为什么java不支持构造函数继承?不允许这种继承有什么好处吗?

假设构造函数继承的...然后因为每个类最终都从 Object 派生,每个类都会最终得到一个无参数的构造函数.这是个坏主意.您到底期望什么:

Suppose constructors were inherited... then because every class eventually derives from Object, every class would end up with a parameterless constructor. That's a bad idea. What exactly would you expect:

FileInputStream stream = new FileInputStream();

做什么?

现在可能应该有一种方法可以轻松创建相当常见的传递"构造函数,但我认为它不应该是默认值.构造子类所需的参数通常与超类所需的参数不同.

Now potentially there should be a way of easily creating the "pass-through" constructors which are fairly common, but I don't think it should be the default. The parameters needed to construct a subclass are often different from those required by the superclass.