Solution: Create a Hierarchy of Inheritance
Look at the solution to the previous challenge.
We'll cover the following...
Problem statement
Explore inheritance hierarchies by following these steps:
Create a class named
Shape
with properties namedHeight
,Width
, andArea
.Add three classes that derive from it:
Rectangle
,Square
, andCircle
with any additional members you feel are appropriate and that override and implement theArea
property correctly.In
Program.cs
, add statements to create one instance of each shape, as shown in the following code:
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:
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 itsheight
andwidth
properties, which are3
and4.5
, respectively.The
Square
object is constructed with a single value representing its side length; in this case, it’s set to5
.The
Circle
object is constructed with a single value, ...