如何创建类中可访问的实例数组?

时间:2015-02-03 13:25:39

标签: java arrays

我正在编写一个代码,用于在另一个类(Bank)中创建Account对象的实例数组。

我正在main方法中初始化数组,但是在Bank类中无法访问它。 我想要做的是创建Account类的4个实例,并能够在Bank类方法中执行所有任务。有没有办法可以做到这一点?

这是我的代码

Account.java

package question1;

import java.util.Date;

public class Account {

    public int AccountNum;
    public double BALANCE;
    public Date OPENDATE;
    public String OwnerName;

    public Account() {
        // TODO Auto-generated constructor stub
    }

    public Account(int accnum, double balance, Date opendate, String ownername) {

        this.AccountNum = accnum;
        this.BALANCE = balance;
        this.OPENDATE = opendate;
        this.OwnerName = ownername;

    }

    public int getAccountNum() {
        return AccountNum;
    }

    public void setAccountNum(int accountNum) {
        AccountNum = accountNum;
    }

    public double getBALANCE() {
        return BALANCE;
    }

    public void setBALANCE(double bALANCE) {
        BALANCE = bALANCE;
    }

    public Date getOPENDATE() {
        return OPENDATE;
    }

    public void setOPENDATE(Date oPENDATE) {
        OPENDATE = oPENDATE;
    }

    public String getOwnerName() {
        return OwnerName;
    }

    public void setOwnerName(String ownerName) {
        OwnerName = ownerName;
    }

    public double yearlyInterest(double balace) {
        return balace;
    }
}

Bank.java

package question1;

public class Bank  {


    public static void main(String[] args) {

        Account[] acc = new Account[4];

        for(int i = 0 ; i<acc.length; i++){
            acc[i] = new Account();
            System.out.println(acc[i].toString());

        }

        /// how to continue form here ??


    }


}

2 个答案:

答案 0 :(得分:0)

您可能希望在班级中拥有Account数组的属性

您可以在课程体中设置您的属性:

public class Bank {

  //Set your property here.
  private Account[] _acc;

  //Initialize in ctor.
  public Bank() {
    _acc = new Account[4];
  }
  //....
  //You can then use it as a property in your code.

  //If needed outside the class, set up setter and getter methods,
  //avoiding violating encapsulation.
  public Account[] getAcc(){
    return _acc;
  }

  public void setAcc(Account acc){
    this._acc = acc;
  }

  //If you need this to be used inside main, then you must instantiate a
  //Bank in main and then make all the appropriate operations there.
  public static void main(String[] args) {

    Bank bank = new Bank();
    Account[] bankAccounts = bank.getAcc();
    //....
  }

}

我的建议是你使用ArrayList代替: 设置属性:

private List<Account> acc;

在构造函数中:     acc = new List();

要在类方法中添加帐户:

acc.add(new Account());

为了通过索引来检索元素:

acc.get(0);

有关详细信息,请查看ArrayList JavaDoc

如果您无法理解为什么在Bank类中无法访问main中定义的数组,那么我建议您更多地搜索面向对象的编程,类定义,实例化和属性可访问性Java中的操作和静态方法。

答案 1 :(得分:0)

调用Account类的构造函数。现在您可以根据需要设置所有参数。之后,您可以将实例添加到任何数组或集合中。

List<Account> accounts = new ArrayList<Account>(4);

Account myAccount = new Account(123, 100.5, new Date(), "dev leb");
accounts.add(myAccount);
相关问题