2014-09-20 81 views
0

這裏是我的超類問題得到構造繼承正確

public class BankAccount 

    { 
     double balance; 
     public BankAccount(double initialBalance) 
     { 
      this.balance = initialBalance; 
     } 
     public void deposit(double amount) 
     { 
      balance += amount; 
     }  
     public void withdraw(double amount) 
     { 
      balance -= amount; 
     }  
     public double getBalance() 
     { 
      return balance; 
     }   
     public void transfer(double amount, BankAccount other) 
     { 
      balance -= amount; 
     }  
    } 

下面是擴展類是

public class CheckingAccount extends BankAccount 
{ 
    int transactionCount; 
    double fee; 
    public CheckingAccount(double initialBalance) 
    { 
     this.balance = initialBalance; 
     this.transactionCount = 0;   
    }  
    public void deposit(double amount) 
    { 
     balance += amount; 
     transactionCount += 1; 
    } 
    public void withdraw(double amount) 
    { 
     balance -= amount; 
     transactionCount += 1; 
    }  
    public void deductFees() 
    { 
     if(transactionCount > 3) 
     { 
      fee = 2.0*(transactionCount-3); 
     }  
     balance -= fee; 
     transactionCount = 0; 
    }  
} 

構造工作正常的超類,但是當我嘗試以擴展類我得到的錯誤,構造函數不能應用於給定的類型,即使我正在申請一個雙重的,就像它是在超類。我剛開始學習繼承類,所以任何輸入是非常讚賞

+0

調用'super(whatever) '在你的子類的構造函數的頂部。 – khelwood 2014-09-20 17:24:33

回答

2

您需要使用super關鍵字來調用您的父母的構造函數。你的父類不會沒有一些參數傳遞給它的定義,所以你可以做這樣的:

public CheckingAccount(double initialBalance) { 
    super(initialBalance); 
    this.transactionCount = 0;   
}  
0

你的情況是你沒有在你的超類定義默認構造函數。如果你將添加下面的構造函數,你將不會有錯誤。

public BankAccount(){ 
    //default constructor 
} 

當您嘗試實例化您的子類時,將會首先調用您的超類的默認構造函數。所以,你可以添加默認consturctor到您的BankAccount我說了,裏面寫

public BankAccount() { 
    System.out.println("loading superclass default"); 
} 

在子類中寫

public CheckingAccount(double initialBalance) { 
    System.out.println("loading subclass"); 
    this.balance = initialBalance; 
    this.transactionCount = 0; 
} 

然後嘗試

CheckingAccount acc = new CheckingAccount(52); 

而且你會看到結果:

loading superclass default 
loading subclass