Create an object from another class

Asked

Viewed 7,392 times

3

I own the class Endereco and the class Cliente, I built 2 builders for the Cliente, and in one of them is to be inserted the name of the client and an object of type Endereco, which works perfectly, but in the other constructor is to be inserted the name of Cliente and create an object of the type Endereco together, the problem is that after entering the data from Endereco, give insight and Endereco is considered null.

Essential part(2 constructors) of the Addressee class:

public class Endereco{
    private String logradouro;
    private String numero;
    private String complemento;
    private String telefone;
    private String celular;
    private String email;

    public Endereco(String log, String num, String comp, String tel, String cel, String mail){
        logradouro = log;
        numero = num;
        complemento = comp;
        telefone = tel;
        celular = cel;
        email = mail;
    }    
    public Endereco(){
        Teclado t = new Teclado();
        logradouro = t.leString("Informe o logradouro: ");
        numero = t.leString("Informe o numero: ");
        complemento = t.leString("Informe o complemento: ");
        telefone = t.leString("Informe o telefone: ");
        celular = t.leString("Informe o celular: ");
        email = t.leString("Informe o e-mail: ");
    }
}

Essential part of the Customer class:

public class Cliente{

    private String nome;
    private Endereco endereco;
    private int pontos;

    public Cliente(String nm, Endereco ed){
        nome = nm;
        endereco = ed;
        pontos = 0;
    }
    public Cliente(String nm){
        nome = nm;
        Endereco e = new Endereco();
    }
}
  • Put in Endereco e, swap for this.endereco = new Endereco(), because you’re creating another objeto of the classe Addressee, that does not match the private created within the Client class ...

3 answers

5


Instead:

Endereco e = new Endereco();

Do it

this.endereco = new Endereco();

You forgot to assign the new instance to the class attribute.

  • thanks my, a silly and simple mistake even but I would never turn myself hahaha

3

I think the problem is in how you declare the Address in the second constructor you should use the variable privada endereco and not declare another.

private String nome;
private Endereco endereco;
private int pontos;

public Cliente(String nm, Endereco ed){
    nome = nm;
    endereco = ed;
    pontos = 0;
}
public Cliente(String nm){
    nome = nm;
    endereco = new Endereco(); // use a variável privada
}

1

Just Instantiate the object giving a new in the Address inside the constructor without parameter, it was null because it was not instantiated

this.endereco = new  Endereco();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.