What is inheritance?

Inheritance is a feature of object-oriented programming languages that allows objects to be based upon or derived from other objects. Essentially, you can make new classes from pre-existing classes.

For example, if you had an “Animal” class that has a “breathe()” method and you wanted to create a “Dog” class, you wouldn’t want to write a breathe method for your dog class. You already did that in the animal class and the dog is definitely going to need to breathe. To prevent yourself from having to write a new breathe method for your dog class, you could have dog inherit from the animal class.

In Inheritance, you can either extend the pre-existing class or override it’s existing functionality. For example, if you would like for your dog to breathe in a different way from every other animal then you could override the breathe method to make the dog breathe under water or something. Naturally the dog should have some things about it that are different from other animals. Barking, for example, seems unique enough about dogs. You could have your dog extend the animal class to include barking.

When would you use it?

I’m not sure how one would write code in an object-oriented language without using inheritance. It’s possible but it would be tedious to create and very difficult to maintain. Regardless, you’d use inheritance anytime you’d like to avoid “reinventing the wheel”. Inheritance goes hand-in-hand with Polymorphism (an important concept in object-oriented programming wherein objects function interchangeably). You’d use it anytime you’re developing a program in an object oriented language.

Why is it valuable?

Inheritance is a way of preventing rework and encourage reuse. Why rewrite all that logic of an existing class if you only want to change one thing about it?

In short, Inheritance makes code easier to organize and understand.