Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Jamie Wyton
3,011 Pointsthis
using the new 'this' command has got me lost a bit. I'm ok with it being used in the MapLocation constructor and that it takes the current object as the argument to be carried over as it calls on the OnMap method. But on the receiving end of OnMap the argument type is Point point! How is this compatible?
1 Answer
andren
28,558 PointsIt's compatible because MapLocation is a class that inherits from Point as you can see if you look at it's declaration:
class MapLocation : Point
The : Point means that it inherits from Point. The fact that it inherits from Point means that a MapLocation object can safely be treated as a Point object since it contains all methods and properties that a Point object would have.
Jamie Wyton
3,011 PointsJamie Wyton
3,011 Pointsso in the case of the arguments (int x, int y, Map map) - would they then be discarded?
andren
28,558 Pointsandren
28,558 PointsAny property unique to the
MapLocationclass would not be accessible while it is being classified as aPointobject.That means
mapwould indeed not be accessible,xandyon the other actually would be. Because those arguments are passed to thePointconstructor when theMapLocationobject is created.public MapLocation(int x, int y, Map map) : base(x, y)The
: base(x, y)part of the constructor tells C# to call the constructor of the parent class (Pointin this case) with the arguments provided. Soxandyare passed toPointwhich means that those are present even when the object is treated as aPoint.Whenever a class inherits from another class it always has to call the constructor of it's parent to pass it whatever arguments it needs to create a valid instance of that class.
Put as simply as possible
MapLocationis aPointobject that just has some properties and methods not present inPoint, all that happens when it gets treated (cast is the technical term) as aPointobject is that those unique properties and methods are no longer accessible. SinceMapLocationis guaranteed to have all of the properties and methods that thePointclass has it is completely safe to treat it as that object.