5
Hello, I am doing a project for college where I have to implement 3 classes. These classes inherit from each other as in the model below:
public class AssinanteFree {
protected int id;
public int getId() { return id; }
public void setId(int v) { id = v; }
protected String nome;
public String getNome() { return nome; }
public void setNome(String v) { nome = v; }
}
public class AssinantePremium extends AssinanteFree {
protected double pontos;
public double getPontos(){ return pontos; }
public void setPontos(double v) { pontos = v; }
}
public class AssinanteVip extends AssinantePremium {
protected String criadoEm;
public String getCriadoEm() { return criadoEm; }
public void setCriadoEm(String v) { criadoEm = v; }
}
I have to make the persistence of objects created in a file, so I created a file that simulates a database, so:
public class Db {
// construtores
private Db() {
assinantes = new ArrayList<>();
}
private Db(int i) throws IOException {
try {
get();
} catch (IOException e) {
assinantes = new ArrayList<>();
set();
}
}
// implementação singleton
private static Db instance;
public static Db getInstance() throws IOException {
return instance == null ? instance = new Db(0) : instance;
}
// getters & setters
private ArrayList<AssinanteFree> assinantes;
public ArrayList<AssinanteFree> getAssinantes() {
return instance.assinantes;
}
public void setAssinantes(ArrayList<AssinanteFree> v) {
assinantes = v;
}
// persistencia
private void get() throws IOException {
try (FileReader reader = new FileReader("db.json")) {
Gson gson = new Gson();
instance = gson.fromJson(reader, Db.class);
}
}
private void set() throws IOException {
try (Writer writer = new FileWriter("db.json")) {
Gson gson = new GsonBuilder().create();
gson.toJson(this, writer);
}
}
}
My problem is this, if in my "database" I have a type AssinanteFree
to the list assinantes
, when the class saves in file it does not save the other properties of the extended classes and, If I persist the deepest class in the inheritance, when making a query of the data I have to keep converting the same.
How to solve?
Let me get this straight... so in theory I have 3 Arraylist’s where in the first I have the
AssinanteFree
, in the second I have the complement ofAssinantePremium
and in the third I have the complement ofAssinanteVip
?– LeandroLuk
In my first idea, yes, each simulating a table. I’m writing another idea now with just a single table.
– Dherik
Because at first I was doing with only 1 table, the problem is that when doing the inverse conversion was not very "cool"
– LeandroLuk
I believe that if I really do as you say it looks better... because so if I really want to know the person’s type, or I can search in the other Arraylists the id or I can add a type field in the free... so it solves the problem...
– LeandroLuk
I edited and added another option, using the same Arraylist.
– Dherik