[英]resolving bracketing error when creating constructors in Java
當我嘗試在以下程序中打開第二個構造函數時,在Eclipse中出現括弧錯誤(第15和18行)“ public Account myCustomAccount ... balance = initial balance;}”。 該程序適用於Dietel“編程入門”第9章練習7。
我懷疑自己在錯誤地創建了構造函數。 您提供什么建議? (提前謝謝您!!)
import java.util.Date;
public class Account {
//declare required variables
private int id = 0;
private double balance = 0;
private double annualInterestRate = 0; //assume all accounts have the same interest rate
private Date dateCreated = new Date(); //no-argument instance stores the present date
//define default & custom constructors
public Account mydefaultaccount = new Account(); //no-argument instance of Account
public Account myCustomAccount = new Account(int identNum, double initialBalance) {
id = identNum;
balance = initialBalance;
}
//define getters
public int getId() {
return id;
}
public double getBalance() {
return balance;
}
public double annualInterestRate() {
return annualInterestRate;
}
public Date getDate() {
return dateCreated;
}
//define setters
public void setId(int idSetter) {
id = idSetter;
}
public void setBalance(double balanceSetter) {
balance = balanceSetter;
}
public void setAnnualInterestRate(double annualSetter) {
annualInterestRate = annualSetter;
}
//define required monthly interest rate getter
public double getMonthlyInterestRate() {
double moInt = annualInterestRate / 12;
return moInt;
}
//define modifiers
public double withdraw(int withdraw) {
balance = balance - withdraw;
}
public double deposit(int deposit) {
balance = balance + deposit;
}
}
那不是定義構造函數的方式。 構造函數應遵循以下形式:
public className(parameters) {}
然后,要實例化該類,請調用:
ClassName variable = new ClassName(Parameters);
就你而言
public Account() {
/* Body */
}
public Account(int identNum, double initialBalance) {
/* Body */
}
並實例化
Account ac = new Account(Parameters);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.