Inheritance Simply

Basics are important. Involving in big projects may make us underestimate and forget about the basics. While I was rechecking the important feature of OOP: inheritance, I wanted to share very simple example briefly.

My little piece of code here calculates the surface and volume of a rectangular prism and calculates its cost based on its volume.

Firtly, I created a base class which is called RectangularPrism, added three number we need for calculation: length,width,height, created the public constructor and then created the methods for calculating volume, surface and displaying the all features of the rectangular prism.


class RectangularPrism
{
protected double length;
protected double width;
protected double height;

public RectangularPrism(double l,double w,double h)
{
length = l;
width = w;
height = h;
}
public double GetSurface()
{
return (2 * ((length * width) +(length * height) +(width * height)));
}

public double GetVolume()
{
return length * width * height;
}
public void Display()
{
Console.WriteLine("Length: {0}",length);
Console.WriteLine("Width: {0}",width);
Console.WriteLine("Height: {0}",height);
Console.WriteLine("Surface: {0}", GetSurface());
Console.WriteLine("Volume: {0}", GetVolume());
}
}

Next, I created another class called Box inherited from RectangularPrism. Additional to the features of base class, Box class has a method to calculate the cost according to its volume. (Volume x 2 is my formula for calculating the cost). It has also a Display() method which runs base.Display and runs an additional Console.Write method.


class Box : RectangularPrism
{
public Box(double l, double w, double h) : base(l,w,h)
{ }

public double GetCost()
{
double cost;
cost = GetVolume() * 2;
return cost;

}

public new void Display()
{
base.Display();
Console.WriteLine("Cost: {0}", GetCost());
}
}

Lastly, we can use our classes and create and object in our main method of the class.


class Program
{
static void Main(string[] args)
{
Box myBox = new Box(8,4,4);
myBox.Display();
Console.ReadLine();

}
}

With those numbers, it will give us following result:

inheritance_csharp

Inheritance, together with encapsulation and polymorphism, is one of the three primary characteristics (or pillars) of object-oriented programming. Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes.

For more information from msdn >>

Advertisements
This entry was posted in C# and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s