Java构造函数继承 [英] Java Constructor Inheritance
问题描述
我想知道为什么在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);
}
}
此代码重复,和无用的(IMHO)...所以再次提出了问题:
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.
这篇关于Java构造函数继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!