Add item to ArrayList every time an object is instantiated

1

I have 3 classes: Client, Account and Bank.

public class Cliente {
  private String nome;
  private String telefone;

  public Cliente(String n, String t){
    this.nome = n;
    this.telefone = t;
}
(...) + getters e setters
}


public class Conta {
private int numero;
private double saldo;
private Cliente cli;
private Banco banco;

public Conta(Cliente c, int n){
    this.cli = c;
    this.numero = n;
} + getters e setters }


public class Banco {
private ArrayList<Conta> contas;

public Banco(){
    contas = new ArrayList<Conta>();
}

Using more or less this structure, I need every time an Account is created, it should be added to the ArrayList Bank class accounts.

    
asked by anonymous 28.09.2015 / 19:51

1 answer

1

It depends a lot on your modeling, you first have to decide who will belong to who, and what makes sense to be created without being associated with someone.

Example: Is it possible to create a client that does not have an account? According to what your code shows so far, yes. But is this desirable? Do not know. Nobody better than you to know that.

Considering that your modeling assists you, what I would change right now is to create a addConta(Conta c) method in the Bank class and pass the object from the bank to the account builder (so no account will be left without a bank associated with it) , and add each new account right in the constructor of class Conta to the list of accounts for that bank. Example:

import java.util.*;

public class Teste {
    public static void main(String [] args){
        Banco b1 = new Banco();
        //.......
        Cliente cli1 = new Cliente("Nome Teste", "Telefone teste");
        Conta cnt1 = new Conta(cli1, 1234, b1);
    }
}

class Cliente {
    private String nome;
    private String telefone;

    public Cliente(String n, String t){
        this.nome = n;
        this.telefone = t;
    }
}

class Conta {
    private int numero;
    private double saldo;
    private Cliente cli;
    private Banco banco;
    public Conta(Cliente c, int n, Banco b){ //passa o objeto de banco para o construtor
        this.cli = c;
        this.numero = n;
        this.banco = b;       //pega a referência do Banco
        banco.addConta(this); //passa a referência da Conta
    }
}

class Banco {
    private List<Conta> contas;
    public Banco(){
        contas = new ArrayList<Conta>();
    }
    public void addConta(Conta c) { //novo método
        this.contas.add(c);
    }   
}
    
28.09.2015 / 20:09