Last post Jan 14, 2016 04:23 PM by ojm37
Jan 14, 2016 04:04 PM|ojm37|LINK
How can I make the compiler enforce the following scenario:
I have an abstract base class of CartItem (for items in a shopping cart) that has a public abstract method called PurchaseItem that each specific item class will implement. So far, so good.
HOWEVER, I now have another class SubscriptionItem that is subclassed from CartItem that is a real class, implements methods, etc (for displaying the various types of subscription items, calculating price, expiration, etc). BUT, I don't want it to implement
PurchaseItem since only the final, specific subscription item knows how to do that.
I've tried something like this, but I get errors:
public abstract class ShoppingCartItem
public int ..... and the rest of the properties and local vars
public ShoppingCartItem(int nItemType)
//implementation of a common constructor that each derived class calls in their constructors
public virtual etc /// the rest of the methods implemented here
public abstract bool PurchaseItem();
public class ShoppingCartSubscriptionItem: ShoppingCartItem
//declarations of properties, etc unique to subscription items
public ShoppingCartSubscriptionItem(int cartID, int... the rest)
//Implementation of common subscription item stuff
public override bool PurchaseItem()
throw new NotImplementedException();
public class NewsSubscription: ShoppingCartSubscriptionItem
public NewsSubscription(int nValue, ... other params)
The code above, I'd like to be able to do something so that the COMPILER makes me implement the PurchaseItem method in NewsSubscription instead of waiting until runtime when the not implemented exception in the ShoppingCartSubscriptionItem is thrown.
NOTE: the code above will not compile. Sort of c# with pseudocode to show what I mean.
Jan 14, 2016 04:11 PM|PatriceSc|LINK
Not tried but it seeems you could just have:
- an abstract CartItem class
- an abstract SubscriptionItem class that implements most methods expect one
- and then the final class that implements this last method
Edit: something like :
public abstract class Abstract1
public abstract bool A();
public abstract bool B();
public abstract class Abstract2: Abstract1
// Implement only A, B still left for further implementation
public override bool A()
public class Actual:Abstract2
// The compiler will complain if not implemented
public override bool B()
Jan 14, 2016 04:23 PM|ojm37|LINK
OK. I think I got it... Been working on this for weeks (on and off). Within minutes of posting the question, tried something else that seems to work: just make the ShoppingCartSubscriptionItem abstract and don't implement the PurchaseItem method. Then classes
derived from ShoppingCartSubscription have to have the PurchaseItem method!