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 trialleonard stencel
805 PointsHow do you intitialize a variable in a subclass?
The exercise: Challenge Task 1 of 1
The Polygon class represents a 2 dimensional shape. It has a public field named NumSides. Create a new type of polygon called Square. It should have a public readonly field named SideLength thatβs initialized using the constructor. Use base to initialize NumSides to 4.
This is my code that i believe was good up to the point before intializing NumSides to 4.: namespace Treehouse.CodeChallenges { class Polygon { public readonly int NumSides;
public Polygon(int numSides)
{
NumSides = numSides;
}
}
class Square : Polygon
{
public Square(int numSides) : base (numSides)
{
}
public readonly int SideLength;
public Square (int sideLength)
{
SideLength = sideLength;
}
}
}
My Problem: I am having trouble figuring out how to intialize numSides to 4 per the instructions. In the lesson exercise we used seperate files. MapLocation.cs was a subclass of Point.cs. Both of these files were called out in Game.cs. I have tried a host of different things including: setting numSides = 4; inside of public Square putting Polygon numSides = new Polygon(4); outside of class Polygon
It made much more sense to me when separate files were used. Any thoughts/insights would be greatly appreciated.
leonard stencel
805 Pointsleonard stencel
805 PointsI Figured it out. I just needed to specify the 4 when I called the base when I used the subclass Square along with a couple of other rearrangements.
public Square(int sideLength) : base (4)