ABSTRACT CLASSES
Abstract classes, marked by the keyword abstract in the class definition, are typically used to define a base class in the hierarchy. What's special about them, is that you can't create an instance of them - if you try, you will get a compile error. Instead, you have to subclass them, as taught in the post on inheritance, and create an instance of your subclass. So when do you need an abstract class? It really depends on what you do.
To be honest, you can go a long way without needing an abstract class, but they are great for specific things, like frameworks, which is why you will find quite a bit of abstract classes within the .NET framework it self. A good rule of thumb is that the name actually makes really good sense - abstract classes are very often, if not always, used to describe something abstract, something that is more of a concept than a real thing.
In this example, we will create a base class for four legged animals and then create a Dog class, which inherits from it, like this:
If you compare it with the examples in the post about inheritance, you won't see a big difference. In fact, the abstract keyword in front of the FourLeggedAnimal definition is the biggest difference. As you can see, we create a new instance of the Dog class and then call the inherited Describe() method from the FourLeggedAnimal class. Now try creating an instance of the FourLeggedAnimal class instead:
You will get this fine compiler error:
Cannot create an instance of the abstract class or interface 'AbstractClasses.FourLeggedAnimal'
Now, as you can see, we just inherited the Describe() method, but it isn't very useful in it's current form, for our Dog class. Let's override it:
In this case, we do a complete override, but in some cases, you might want to use the behavior from the base class in addition to new functionality. This can be done by using the base keyword, which refers to the class we inherit from:
Now obviously, you can create other subclasses of the FourLeggedAnimal class - perhaps a cat or a lion? In the next post, we will do a more advanced example and introduce abstract methods as well. Read on.
No comments:
Post a Comment