I have a general OO design question that stems from a Hibernate Model.
Example
payment – Base (SuperType)
@Entity
@Table(name = "PAYMENT")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn( name = "type", discriminatorType = DiscriminatorType.STRING)
@DiscriminatorValue("BASE")
public class Payment{
private Product product;
private Date date;
private Customer Customer;
getters/setters
}
CreditCard
@Entity
@DiscriminatorValue("CC")
public class CreditCard extends Payment {
private String Account
getters/setters
}
Cash
@DiscriminatorValue("CASH")
public class Cash extends Payment {
private String Paper
private String Coins
getters/setters
}
Working with hibernate is not a problem (table per class hierarchy). Since Hibernate is able to accept a generic Object instance and still persist the correct instance.
My question is centered around working with the Payment polymorhically in other parts of the code. Since each subclass adds unique instance fields does that mean I need to stub out these subclass fields on Payment itself just to buy the benefit of polymorphism. This does not seem correct in that each time I add a new field to a subclass or a new type of payment I am going back and adding metohods to Payment.
Is there something I am missing, a pattern or somthing inherent to Java I can use?
Thanks
-J
Purely from OO pov (point of view), you should be trying to extract interface to CreditCard or Cash types of transactions. So ideally you shouldn’t have any accessors to variables of sub-class X if you can not implement it for sub-class Y (or better to say at least one other sub-class).
E.g. in this case I would say you could have methods like these in
Payment:which are implemented by all sub-classes. Differently.
Then you get true polymorphism.
If you must access something specific like say Paper or Coin “in other parts of the code”, then those parts of code should
import Cashinstead ofPayment. This is because that piece of code is specific toCashtransactions and not related toCreditCard, so no point in extracting some specific methods inPayment.PS: You said “…Since Hibernate is able to accept a generic Object instance and still persist the correct instance.” ==> This of course is not polymorphism. I donno anything abt Hibernate but I’d guess that it would use RTTI to accomplish this, and that’s like exactly the opposite of polymorphism. 🙂