Object-oriented – How often is Inheritance used

inheritanceobject-oriented

I admit that I am a junior developer, and so far I've only built simple web applications in ASP.NET MVC. But I've never had to use the inheritance aspect of Object Oriented Programming in my own classes! It is true that in using ASP.NET MVC I inadvertently use inheritance (any controller I create will inherit from the base controller class), but I am referring here to the conscious use of inheritance in my design of a particular web system.

Is it because I am a bad programmer? Or could it be that inheritance only comes into play in certain scenarios? Don't get me wrong, I understand what inheritance is and how to code using inheritance if I had to.

I just can't seem to find a scenario to use it at. Basically, I am wondering how often it is used in OO programming in general.

Best Answer

Inheritance is used all the time when writing object-oriented code. In most OO languages, (with C++ being a prominent exception,) all objects have a single "base object" class that they derive from that provides common functionality, so literally everything that uses an object uses inheritance.

Beyond that obvious point, there are many times when you'll find that you need several different types of object that share a lot of important traits in common. Inheritance is very useful here. For example, if you've ever built a GUI in an object-oriented language, you probably used a framework where all of the graphical controls had a common parent class that handled a bunch of functionality that all the controls in the windowing system they run on need to cover. And if you do any work with parsing or code generation, (which are basically two sides of the same coin) you'll quickly run into other examples where a base class with a bunch of derived classes are useful.

It's true that inheritance is not the only way to make objects work together; you can also use composition, (where one object contains another object of a different type,) which works better in some cases. Be careful about treating this as a point of dogma, though. Inheritance is a very useful tool if you know what you're doing. So is composition, and neither one of them is really a good substitute for the other. The important thing is to know what you're doing, and if you don't, learn and experiment and develop your knowledge and your skills. (And feel free to ask questions on here or StackOverflow!)

Related Topic