C# C# Objects Inheritance Inheritance

Its c# objects inheritance The tasks is to come up with a code

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.

1Polygon.cs namespace Treehouse.CodeChallenges 2 { 3 class Polygon 4 { 5 public readonly int NumSides; 6 ​ 7 public Polygon(int numSides) 8 { 9 NumSides = numSides; 10 } 11 } 12 }

What exactly is your question? Please be more specific.

1 Answer

Juan Naputi
Juan Naputi
1,771 Points

We'll start off small and then work our way up.

The first thing that you have to do is make a class called Square and make it have a readonly field called SideLength that is initialized in the constructor. This provides all the information we need to create the class. Without worrying about deriving from the Polygon class, this is what we will have.

// Our basic, happy square.
class Square
{
   public readonly int SideLength;

   public Square(int sideLength)
   {
      SideLength = sideLength;
   }
}

Now, we are told that it is a new type of Polygon. As such, we make our Square class derive (extend) from the Polygon class:

// Notice that we extended from Polygon.
// When you are extending a class, you put a ':' between your class name and the
// class you are extending.
class Square : Polygon
{
   public readonly int SideLength;

   public Square(int sideLength)
   {
      SideLength = sideLength;
   }
}

We are then told to use base to initialize NumSides to 4:

class Square
{
   public readonly int SideLength;

   // Notice the use of base here.  We are calling the 
   // constructor of Polygon passing in the value of 4.
   // This value will be assigned to the Polygons *NumSides* variable.
   public Square(int sideLength) : base(4)
   {
      SideLength = sideLength;
   }
}
Christian Higgins
Christian Higgins
15,757 Points

This is very thorough, Juan, thank you!!