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
提交
取消
