Create an object from another class

3

I have the class Endereco and the class Cliente , I build 2 constructors for Cliente , and one of them is to insert the client name and an object of type Endereco , which works perfectly , but in the other constructor is to insert the name of Cliente and create an object of type Endereco together, the problem is that after typing the data of Endereco , I give inspect and Endereco is considered null .

Essential part (2 constructors) of class Address:

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 Client 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();
    }
}
    
asked by anonymous 11.04.2014 / 16:44

3 answers

5

Instead:

Endereco e = new Endereco();

Do this

this.endereco = new Endereco();

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

    
11.04.2014 / 16:49
3

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

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
}
    
11.04.2014 / 16:49
1

Just instantiate the object giving a new address in the constructor with no parameter, it was null because it was not instantiated

this.endereco = new  Endereco();
    
11.04.2014 / 18:40