Java构造器继承我想知道为什么在java构造函数中没有继承?你知道当你有这样一堂课的时候:public class Super {
public Super(ServiceA serviceA, ServiceB serviceB, ServiceC serviceC){
this.serviceA = serviceA;
//etc
} }稍后,当您继承Super,java会抱怨没有定义默认构造函数。解决方案显然是这样的:public class Son extends Super{
public Son(ServiceA serviceA, ServiceB serviceB, ServiceC serviceC){
super(serviceA,serviceB,serviceC);
}}这个代码是重复的,不是干的和无用的(IMHO).因此,这再次提出了一个问题:为什么java不支持构造函数继承?不允许这种继承有什么好处吗?
3 回答
慕尼黑的夜晚无繁华
TA贡献1864条经验 获得超6个赞
FileInputStream stream = new FileInputStream();
江户川乱折腾
TA贡献1851条经验 获得超5个赞
public class Son extends Super{ // If you dont declare a constructor of any type, adefault one will appear. public Son(){ // If you dont call any other constructor in the first line a call to super() will be placed instead. super(); }}
人到中年有点甜
TA贡献1895条经验 获得超7个赞
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
添加回答
举报
0/150
提交
取消