...

/

Solution: Create a Hierarchy of Inheritance

Solution: Create a Hierarchy of Inheritance

Look at the solution to the previous challenge.

Problem statement

Explore inheritance hierarchies by following these steps:

  1. Create a class named Shape with properties named Height, Width, and Area.

  2. Add three classes that derive from it: Rectangle, Square, and Circle with any additional members you feel are appropriate and that override and implement the Area property correctly.

  3. In Program.cs, add statements to create one instance of each shape, as shown in the following code:

Press + to interact
Rectangle r = new(height: 3, width: 4.5);
WriteLine($"Rectangle H: {r.Height}, W: {r.Width}, Area: {r.Area}");
Square s = new(5);
WriteLine($"Square H: {s.Height}, W: {s.Width}, Area: {s.Area}");
Circle c = new(radius: 2.5);
WriteLine($"Circle H: {c.Height}, W: {c.Width}, Area: {c.Area}");

Step-by-step solution

Let’s look at our solution by comprehensively understanding it.

Let’s have a look at Program.cs file:

Press + to interact
using Packt.Shared;
Rectangle r = new(height: 3, width: 4.5);
WriteLine($"Rectangle H: {r.Height}, W: {r.Width}, Area: {r.Area}");
Square s = new(5);
WriteLine($"Square H: {s.Height}, W: {s.Width}, Area: {s.Area}");
Circle c = new(radius: 2.5);
WriteLine($"Circle H: {c.Height}, W: {c.Width}, Area: {c.Area}");

In this file, we have created a new instances of Rectangle, Square, and Circle class with specific properties as follows:

  • The Rectangle object is constructed with specific values for its height and width properties, which are 3 and 4.5, respectively.

  • The Square object is constructed with a single value representing its side length; in this case, it’s set to 5.

  • The Circle object is constructed with a single value, ...