I am new to Java and I am coding up a modular application made like this:
************* ******* ***********
* * * * * Data *
* Front-end * -------- * API * ------- * Handler *
* * * * * *
************* ******* ***********
Essentially, I want to be able to define an API with N classes, and then have a "Data Handler" module deal with storing the objects somewhere (a database, for example), without the front-end needing to know anything of how that is implemented.
So, let's say I have two classes defined in my API: Contract and Company. I want the front-end to be able to do something like:
myContract = new Contract();
myCompany = new Company();
myContract.setCompany(myCompany);
myContract.save();
myCompany.save();
This way, in the future I could change the way I store the data (the Data Handler module), without changing any code in the front-end.
To do this, I wrote two interfaces for Contract and Company in the API module. Then, in the data handler module I wrote to classes which implement the two interfaces: DbContract and DbCompany.
Now, I am running into issues because I have defined the getter/setter methods in the Contract interface as:
public interface Contract {
public Company getCompany();
public void setCompany(Company company);
}
And implemented them in DbContract as:
public class DbContract implements Contract {
private DbCompany company;
@Override
public Company getCompany() {
return this.company;
}
@Override
public void setCompany(Company company) {
this.company = company;
}
}
However, I am getting class type mismatch errors all over the place... Am I completely missing the point? How should I actually do this?
Thanks in advance for your help.
setCompany
, you can't assign aCompany
to aDBCompany
reference without doing a cast. When / how are you creating aDBCompany
?public Contract createContract() { return new DbContract(); }
. Are casts the right way to go about this?Frontend
operate only with interfaces. By creating objects there, you break this rule.