I have a superclass that handles car decal information. I have a subclass that handles specific decal information for a transaction. I have a special override in the transaction decal that is used to check for certain things before a decal # can be set. The problem I’m having is that sometimes I need to grab information about a generic decal object and set it to my transaction decal. For instance:
TransactionDecal myTransactionDecal = new TransactionDecal();
Decal myGenericDecal = new Decal();
myTransactionDecal = (TransactionDecal) myGenericDecal.getGenericDecal();
But I get a runtime error telling me I can’t cast between the types. What exactly am I doing wrong, and is this the correct way to go about it? Thanks!
The principle of substitutability would indicate that any type can be substibuted by itself or a subtype.
Here, you’re doing the reverse – you’re attempting to reference an instance of the supertype in a variable of the subtype (assuming Decal is the superclass, and TransactionDecal the subclass).
This is blocked, because inheritance exists to specialise an existing class, i.e. to extend the interface; in general, substituting a superclass would limit the interface, and this would allow calls to methods (via the referencing variable type) that are not implemented in the superclass.