Monday, September 8, 2008

What is inheritance


What is Inheritance



The .NET framework has thousands of classes, and each class has many different methods and properties. Keeping track of all these classes and members would be impossible if the .NET framework were not implemented extremely consistently. For example, every class has a ToString method that performs exactly the same task – converting an instance of the class into a string. Similarly many classes support the same operators, such as comparing two instances of a class for equality.
This consistency is possible because of inheritance and interfaces. Use inheritance to create new classes from existing ones.

You can easily create a custom exception class by inheriting from System.ApplicationException, as shown below:

//C#
class DerivedException : System.ApplicationException
{
Public override string Message
{
get { return “An error occurred in the application.”;}
}
}

You can throw and catch the new exception because the custom class inherits that behavior of its base class, as shown here:

//C#
try
{
throw new DerivedException();
}
catch (DerivedException ex)
{
Console.WriteLine(“Source: {0},Error: {1}”, ex.Source, ex.Message);
}

Notice that the custom exception not only supports the throw/catch behavior, but it also includes a Source member (as well as others) inherited from System.ApplicationException.

Another benefit of inheritance is the ability to use derived classes interchangeably. For example, there are five classes that inherit from the System.Drawing.Brush base class: HatchBrush, LinearGradientBrush, PathGradientBrush, SolidBrush and TextureBrush. The Graphics.DrawRectangle method requires a Brush object as one of its parameters; however, tou will never pass an object of the base Brush class to Graphics.DrawRectangle. Instead, you will pass an object of one of the derived classes. Because they are each derived from the Brush class, the Graphics.DrawRectangle method can accept any of them. Similarly, if you were to create a custom class derived from the Brush class, you could also pass an object of that class to Graphics.DrawRectangle.

No comments: