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 trialmichaelcodes
5,604 PointsConfused about the :base constructor and how it works?
I am confused about how the base constructor works. I understand that it takes the parent classes constructor parameter but in what way? In the code below:
public MapLocation(int x, int y, Map map) : base(x,y){
if(!map.OnMap(this)) {
throw new OutOfBoundsException(x + "," + y + " is out of bounds!");
}
Why did we initialize new variables for MapLocation (x and y), but then we also have :base(x,y) if they are not used? Also do these variables need to be named the same as they are in the parent constructor or does it not matter?
This is very confusing to me if anyone can explain how this is working it would be greatly appreciated!
2 Answers
Steven Parker
231,248 PointsThe variables are passed to the parent constructor, because they are used by the parent constructor. They are also used in this constructor to build the exception error message.
The variable names do not have to be the same as in the parent constructor, but doing so might help to make their purpose clear.
Evan Welch
1,815 PointsSo base just refers to the parent class?
michaelcodes
5,604 Pointsmichaelcodes
5,604 PointsI understand a bit better. So when the object is created using:
MapLocation maplocation = new MapLocation(20,20,map);
You are sending the parameters for the MapLocation x and y. Where is the base getting its x and y value? Are they also passed along and are the same as the param values above?
Thanks for the help!
Steven Parker
231,248 PointsSteven Parker
231,248 PointsThe base gets the x and y values from the "
: base(x,y)
" call of the MapLocation constructor. They are passed along unchanged, so in this example they would both be 20.michaelcodes
5,604 Pointsmichaelcodes
5,604 PointsAhh, thank you for all your help I think I have a better understanding now. I am sure it will become more clear as I continue in my learnings.
Take care and happy coding!