I have 3 classes and 1 enum
:
public class Pessoa {
private TipoPessoa tipo;
public TipoPessoa getTipo() {
return tipo;
}
public void setTipo(TipoPessoa tipo) {
this.tipo = tipo;
}
}
public class PessoaF extends Pessoa{
private String cpf;
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
}
public class PessoaJ extends Pessoa{
private String cnpj;
public String getCnpj() {
return cnpj;
}
public void setCnpj(String cnpj) {
this.cnpj = cnpj;
}
}
public enum TipoPessoa {
PESSOAFISICA, PESSOAJURIDICA;
}
I want that when setting a type of person, can create an equivalent instance to the enumerator applied in type:
For example, if the sector is a PERSONAL PHYSICIAN, I could access the members (attributes, fields and methods) of the PersonF class, as it would call the correct constructor:
Pessoa p1 = new PessoaF();
p1.setCpf = 32443265332;
But with inheritance I can not access the members of a child class through an instance created from a parent class. So how to proceed?
I changed the enum, implementing an abstract method that returns the constructor I want to use according to the type of person set:
public enum TipoPessoa {
PESSOAFISICA (0, "Pessoa Fisica") {
@Override
public Pessoa obterPessoa() {
return new PessoaF();
}
},
PESSOAJURIDICA (1, "Pessoa Juridica") {
@Override
public Pessoa obterPessoa() {
return new PessoaJ();
}
};
public abstract Pessoa obterPessoa();
private TipoPessoa(){}
private TipoPessoa(Integer cod, String desc) {
this.cod = cod;
this.desc = desc;
}
private Integer cod;
private String desc;
public Integer getCod() {
return cod;
}
public void setCod(Integer cod) {
this.cod = cod;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
With this modification I'm creating the object as follows:
Pessoa p1 = TipoPessoa.PESSOAFISICA.obterPessoa();
When I request that it print the type of the created object it tells me that it has been created correctly:
System.out.println(p1.getClass());
Retorno : class Pessoas.PessoaF
But I still can not access the setCpf()
method that is within the PessoaF
class.
I want to create a person and according to the value set in the type attribute. And that this object created be able to access the members according to the option of the selected enumerator. How to proceed?