Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Not 100% sure I am reading the question correctly, but I'll give it a shot, taking my cue from this line: "So I would pass in either a BaseType or a ChildType; be able to access the base properties for either object and do what ever logic."</p> <p>So let's assume a function foo that takes a parameter.</p> <p>If you have <code>foo(BaseType b)</code> then:</p> <ul> <li>You can be passed an instance of either BaseType or ChildType</li> <li>You can access all properties defined on BaseType</li> <li>BUT you cannot access the extrafield member without ridiculous casting shenanigans</li> </ul> <p>This is for a very good reason: your function takes BaseType, which has no extrafield, so since it doesn't exist you can't refer to it.</p> <p>If that's okay, then just do this. If you need to access extrafield then you have a small problem.</p> <p>The alternate form of foo is <code>foo(ChildType c)</code> which will mean:</p> <ul> <li>You can only accept instances of ChildType, not instances of BaseType</li> <li>BUT you can access any of the properties, including Name and extrafield</li> </ul> <p>The solution I would first consider here is to extend the signature of BaseType to include extrafield. Polymorphism works best when your signature is consistent across the various levels of the class hierarchy that you want to treat interchangeably. Even if extrafield doesn't make a ton of sense in BaseType you may wish to either make BaseType abstract, or put a no-op implementation of the extrafield there.</p> <p>I would say that if your design calls for having a different signature for the subclass, you will encounter difficulties in treating it as totally interchangeable with the BaseType.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload