It depends a lot on your modeling, you first of all have to decide that it will belong to who, and what it makes sense to be created without being associated with someone.
Example: Is it possible to create a client who does not have an account? According to what your code shows so far, yes. But is it desirable? I don’t know. No one better than you to know that.
Whereas your modeling meets you, what I would change at the moment is to create a method addConta(Conta c)
in the Bank class and pass the bank object to the account constructor (thus no account will be without a bank associated with it), and add each new account logo in the class constructor Conta
the account list of 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);
}
}
Just make your Bank class an account manager and customers, so every time you need to create an account, you will call Bank->add Contact, simply create the account and add it to the array.
– user28595