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贡献1827条经验 获得超8个赞
FileInputStream stream = new FileInputStream();
拉丁的传说
TA贡献1789条经验 获得超8个赞
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();
}}
大话西游666
TA贡献1817条经验 获得超14个赞
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 ClassCastExceptionclass 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
提交
取消
