Thursday, 27 November 2014

C#.NET Tutorial - Day - 17 - Classes - Inheritance


INHERITANCE



One of the absolute key aspects of Object Oriented Programming (OOP), which is the concept that C# is built upon, is inheritance, the ability to create classes which inherits certain aspects from parent classes. The entire .NET framework is built on this concept, with the "everything is an object" as a result of it. Even a simple number is an instance of a class, which inherits from the System.Object class, although .NET helps you out a bit, so you can assign a number directly, instead of having to create a new instance of e.g. the integer class. 

This subject can be a bit difficult to comprehend, but sometimes it help with some examples, so let's start with a simple one of those:




First, we define an Animal class, with a simple method to output a greeting. Then we define a Dog class, and with a colon, we tell C# that the Dog class should inherit from the Animal class. The beautiful thing about this is that it makes sense in the real world as well - a Dog is, obviously, an Animal. Let's try using the classes:




If you run this example, you will notice that even though we have not defined a Greet() method for the Dog class, it still knows how to greet us, because it inherits this method from the Animal class. However, this greeting is a bit anonymous, so let's customize it when we know which animal it is:




Besides the added method on the Dog class, you should notice two things: I have added the virtual keyword to the method on the Animal class, and on the Dog class, I use the override keyword. 

In C#, you are not allowed to override a member of a class unless it's marked as virtual. If you want to, you can still access the inherited method, even when you override it, using the base keyword.




Methods is not the only thing to get inherited, though. In fact, pretty much all class members will be inherited, including fields and properties. Just remember the rules of visibilty, as discussed in a previous post. 

Inheritance is not only from one class to another - you can have a whole hierarchy of classes, which inherits from eachother. For instance, we could create a Puppy class, which inherits from our Dog class, which in turn inherits from the Animal class. What you can't do in C#, is to let one class inherit from several other classes at the same time. Multiple inheritance, as it's called, is not supported by C#.




No comments:

Post a Comment