Lets say we wish to represent a Person
public interface Person {
String getFirstName();
String getLastName();
}
This is implemented with JPA (code I am missing out since it is pretty banal)
Now, I wish to have a Model, the interface of which is an extension of the person interface with setter methods
public interface PersonModel extends Person {
void setFirstName(String firstName);
void setLastName(String lastName);
}
and I implement a concrete implementation of the Model interface (which I am skipping since its pretty banal again)
In doing this I realised that the PersonModel extending from Person doesn't really make that much sense since a "PersonModel is not a Person"
It is also not "correct" to cast a PersonModel to Person.
What is the correct way to implement this - PersonModel could just not inherit from Person and re-define the methods but that means extra maintenance.
I could extract the methods to another base interface -> PersonBase(?) and extend both Person (no other methods defined) and PersonModel from that.
If I am going down the above path, what would be the best way to name the base interface?
One of the main reasons I am using interfaces (apart from the fact that it helps me in thinking through about how everything would work / fit together) is so that there can easily be different implementation layers (JPA2/NoSQL Driver etc.)
This is not real code being used, so please excuse any syntax errors / typos - I just wrote it up for the purpose of this question.
Thoughts / guidance / advice appreciated.
Upcasting seems to work fine:
package person;
public class PersonApp {
public static void main(String [] args)
{
ConcretePerson p = new ConcretePerson("Superman");
System.out.println(p.getName());
PersonModel pm= p;
System.out.println(pm.getName());
Person pn=p;
System.out.println(pn.getName());
Person pnm=pm;
System.out.println(pnm.getName());
}
}
program output:
Superman
Superman
Superman
Superman
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.