0
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 you to be able to create an instance equivalent to the enumerator applied to the type:
For example, if I was able to access the members (attributes, fields and methods) of the Personal class, I could access it, because it would call the correct constructor:
Pessoa p1 = new PessoaF();
p1.setCpf = 32443265332;
But with inheritance I cannot access the members of a daughter class through an instance created from a parent class. So how to proceed?
I modified Enum, implementing an abstract method that returns me 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 am creating the object as follows:
Pessoa p1 = TipoPessoa.PESSOAFISICA.obterPessoa();
When I ask him to print the type of the created object he tells me he created it correctly:
System.out.println(p1.getClass());
Retorno : class Pessoas.PessoaF
But I still can’t access the method setCpf()
that is within the class PessoaF
.
I want to create a person and according to the value set in the type attribute. And that this created object can access members according to the selected enumerator option. How to proceed?
can give an example, your question is not very clear
– Costamilam
Hello, as in the image. I have a class Person who has as a daughter the Personal Physical class, each has its methods and attributes. I want the child class when I seal it from the parent class to still have visibility on its own attributes. What it shows in the picture is just this, I can not have visibility of any method of the Personal Physique class.
– Gonzaga Neto