为什么我的构造函数被认为是方法?

时间:2014-11-07 22:36:26

标签: java class object constructor

我正在制作一个将银行账户作为对象的程序。这些帐户具有利率,余额,ID和日期创建数据。根据我的理解,默认余额,ID和兴趣是0。默认情况下,利率未定义。我正在学习的那本书表明,使用“Circle(){}”完成了一个无参数的构造函数。我在帐户类中使用了“account(){}”。当我在jGRASP中运行程序时,我得到两个构造函数的错误“无效的方法声明;返回类型”。它正在认识到我打算将构造函数作为方法。我需要了解什么才能使我的构造函数不被识别为方法?

运行第一个构造函数时,我知道我们使用默认值创建一个名为account的Account对象。当我们运行第二个构造函数时,我们将帐户对象的值更改为具有指定

的值
public class Bank{

public static void main(String[] args){

Account account = new Account(1122, 20000);

account.setAnnualInterestRate(4.5);

account.withdraw(2500);

account.deposit(3000);


   System.out.println("Balance is " + account.getBalance());

   System.out.println("Monthly interest is " + account.getMonthlyInterest());

   System.out.println("This account was created at " + account.getDateCreated());

                                     }

                             }


  class Account {

             private int id = 0;

             private double balance = 0;

             private double annualInterestRate = 0;

             private String dateCreated;



              account(){

              }

             account(int newID, double newBalance){

             id = newID;

             balance = newBalance;

             }

        //accessor for ID
        public int getID(){
        return id;
        }
        //acessor for balance
        public double getBalance(){
        return balance;
        }
        //accessor for interest rate
        public double getAnnualInterest(){
        return annualInterestRate;
        }
        //mutator for ID
        public void setID(int IDset){
        id = IDset;
        }
        //mutator for balance
        public void setBalance(int BalanceSet){
        balance = BalanceSet;
        }
        //mutator for annual interest
        public void setAnnualInterestRate(double InterestSet){
        annualInterestRate = InterestSet;
          }
        //accessor for date created
        public String getDateCreated(){
        return dateCreated;
        }
        //method that converts annual interest into monthly interest and returns the value
        public double getMonthlyInterest(){
        double x =  annualInterestRate / 12;
        return x;
          }
       //method that witdraws from account
       public double withdraw(double w){
       balance -= w;
       return balance;
       }
       //method that deposits into account
       public double deposite(double d){
       balance += d;
       return balance;
       }




  }

3 个答案:

答案 0 :(得分:10)

构造函数名称必须与区分大小写方式中的类名匹配。在Account课程中,更改

account(){

Account(){

同样适用于你的其他构造函数。

答案 1 :(得分:4)

您需要在两个构造函数中大写a。 Java区分大小写。

          Account(){

          }

         Account(int newID, double newBalance){

             id = newID;

             balance = newBalance;

         }

否则,Java将此视为没有返回类型的方法。请记住,构造函数没有或不需要返回类型。

答案 2 :(得分:0)

构造函数应该是camelized(作为约定,与类名相同)并且它只返回自身的类型 看我的例子:)

Account() {
 return;
}