I have a following model:
abstract Article {id, name, text}
final NewspaperArticle { printDate } extends Article
final ScientificArticle { quotations, publicationDate } extends Article
final ... { ... } extends Article
I wonder how I could achieve casting the final entities between each other, so that the common fields of Article superclass would be set and the different fields would stay null. Something like:
ScientificArticle scientificArticle = ...;
NewspaperArticle newspaperArticle = new NewspaperArticle();
newspaperArticle.copyOf(scientificArticle);
Is it possible to cast it or I will have to use reflection?
To answer your question in short: No, you can’t cast an object to another class. You may only cast to supertypes of the object’s real class. (A class is also a supertype of itself.)
You could, however, use composition instead of inheritance:
Then you could add a constructor like
NewspaperArticle(Article createFrom)to each class which sets the article data field and leaves the others null:Your example would then look like: