Hello, I'm 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 persist the created objects in a file, so I created a file that simulates a database, like this:
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 AssinanteFree
type for the assinantes
list, when the class saves to a file it does not save the other properties of the extended classes and, if I I persist the deepest class in the inheritance, when making a query of the data I have to be converting the same ones.
How to solve?