Search⌘ K

Solution Review: Implement the Rectangle Class

Explore how to implement a Rectangle class in C# by applying data hiding principles through private fields and constructors. Understand encapsulation as you create methods like GetArea and instantiate objects to see these concepts in action.

We'll cover the following...

Solution

C#
// Class Rectangle
class Rectangle {
// Private Fields
private int _length;
private int _width;
// Parameterized Constructor
public Rectangle(int length, int width) {
this._length = length;
this._width = width;
}
// Method to calculate Area of a rectangle
public int GetArea() {
return this._length * this._width;
}
}
class Program {
public static void Main(){
Rectangle obj = new Rectangle(2,2);
System.Console.WriteLine(obj.GetArea());
}
}

Explanation

The solution is straightforward.

...